Example output
import React from 'react';
import { render } from 'react-dom';
import { createStore, applyMiddleware } from 'redux';
import { Provider } from 'react-redux';
import thunk from 'redux-thunk';
import { createSlice } from 'redux-toolkit';
import axios from 'axios';
import { List, Typography } from 'antd';
const initialState = {
pokemons: [],
loading: false,
error: null,
};
const pokemonsSlice = createSlice({
name: 'pokemons',
initialState,
reducers: {
fetchPokemonsStart(state) {
state.loading = true;
},
fetchPokemonsSuccess(state, action) {
state.loading = false;
state.pokemons = action.payload;
},
fetchPokemonsError(state, action) {
state.loading = false;
state.error = action.payload;
},
},
});
const {
fetchPokemonsStart,
fetchPokemonsSuccess,
fetchPokemonsError,
} = pokemonsSlice.actions;
const fetchPokemons = () => async (dispatch) => {
try {
dispatch(fetchPokemonsStart());
const response = await axios.get('https://pokeapi.co/api/v2/pokemon?limit=151');
const pokemons = response.data.results.map((pokemon, index) => ({
...pokemon,
id: index + 1,
image: `https://raw.githubusercontent.com/PokeAPI/sprites/master/sprites/pokemon/${index +
1}.png`,
}));
dispatch(fetchPokemonsSuccess(pokemons));
} catch (err) {
dispatch(fetchPokemonsError(err.message));
}
};
const store = createStore(pokemonsSlice.reducer, applyMiddleware(thunk));
const App = () => {
const { pokemons, loading, error } = store.getState();
React.useEffect(() => {
store.dispatch(fetchPokemons());
}, []);
if (loading) return <div>Loading...</div>;
if (error) return <div>{error}</div>;
return (
<List
itemLayout="horizontal"
dataSource={pokemons}
renderItem={(pokemon) => (
<List.Item>
<List.Item.Meta
avatar={<img src={pokemon.image} alt={pokemon.name} />}
title={<Typography.Text strong>{pokemon.name}</Typography.Text>}
/>
</List.Item>
)}
/>
);
};
render(
<Provider store={store}>
<App />
</Provider>,
document.getElementById('root')
);