Example input
Programming Language to Code: Create React App, yarn, Ant Design, List, Redux Toolkit, createSlice, thunk, axios
Description: Create Pokemon App that lists pokemons with images that come from PokeAPI sprites endpoint
File Type: .js
Example output
import React from "react";
import ReactDOM from "react-dom";
import { BrowserRouter as Router, Route } from "react-router-dom";
import { Provider } from "react-redux";
import { configureStore } from "@reduxjs/toolkit";
import { createSlice } from "@reduxjs/toolkit";
import { thunk, axios } from "redux-thunk";
import { List } from "antd";
// Create reducer
const pokemonSlice = createSlice({
name: "pokemon",
initialState: {
pokemons: [],
loading: false
},
reducers: {
setPokemons: (state, action) => {
state.pokemons = action.payload;
},
setLoading: (state, action) => {
state.loading = action.payload;
}
}
});
const { setPokemons, setLoading } = pokemonSlice.actions;
// Configure store
const store = configureStore({
reducer:continue
pokemonSlice.reducer
});
// Fetch pokemons
const fetchPokemons = () => {
return async dispatch => {
dispatch(setLoading(true));
const response = await axios.get("https://pokeapi.co/api/v2/pokemon?limit=151");
const pokemons = response.data.results.map(pokemon => {
const spriteResponse = axios.get(
`https://pokeapi.co/api/v2/pokemon/${pokemon.name}`
);
pokemon.sprite = spriteResponse.data.sprites.front_default;
return pokemon;
});
dispatch(setPokemons(pokemons));
dispatch(setLoading(false));
};
};
// Main component
const App = () => (
<Provider store={store}>
<Router>
<Route
exact
path="/"
render={() => (
<List
bordered
dataSource={store.getState().pokemons}
renderItem={pokemon =>
(
<List.Item>
<img
src={pokemon.sprite}
alt={pokemon.name}
width="48px"
height="48px"
/>
{pokemon.name}
</List.Item>
)}
/>
)}
/>
</Router>
</Provider>
);
// Initialize
ReactDOM.render(<App />, document.getElementById("root"));
store.dispatch(fetchPokemons());