Skip to content

Instantly share code, notes, and snippets.

@ozcanzaferayan
Created December 17, 2022 22:20
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ozcanzaferayan/e0f568b71926d505574e37eeda1acac3 to your computer and use it in GitHub Desktop.
Save ozcanzaferayan/e0f568b71926d505574e37eeda1acac3 to your computer and use it in GitHub Desktop.
I want you to act as a Senior Frontend developer. I will describe a project details you will code project with this tools: Create React App, yarn, tailwindCSS, Redux Toolkit, createSlice, thunk, axios. You should only reply file contents, and nothing else. Do not write explanations. My first request is "Create Pokemon App that lists pokemons"
import React from "react";
import ReactDOM from "react-dom/client";
import {
createSlice,
configureStore,
createAsyncThunk,
} from "@reduxjs/toolkit";
import { Provider, useDispatch, useSelector } from "react-redux";
import axios from "axios";
import "./index.css";
// Create an async thunk for fetching the list of pokemons
export const fetchPokemons = createAsyncThunk(
"pokemons/fetchPokemons",
async () => {
const response = await axios.get("https://pokeapi.co/api/v2/pokemon");
return response.data;
}
);
// Create the redux slice for the pokemons list
const pokemonsSlice = createSlice({
name: "pokemons",
initialState: {
pokemons: [],
loading: false,
error: null,
},
reducers: {},
extraReducers: {
// Handle the success and failure actions of the async thunk
[fetchPokemons.pending]: (state) => {
state.loading = true;
},
[fetchPokemons.fulfilled]: (state, action) => {
state.loading = false;
state.pokemons = action.payload.results;
},
[fetchPokemons.rejected]: (state, action) => {
state.loading = false;
state.error = action.error;
},
},
});
// Create the redux store
const store = configureStore({
reducer: pokemonsSlice.reducer,
});
function App() {
const dispatch = useDispatch();
const { pokemons, loading, error } = useSelector((state) => state);
// Dispatch the async thunk when the component mounts
React.useEffect(() => {
dispatch(fetchPokemons());
}, [dispatch]);
if (loading) {
return <div className="text-3xl font-bold text-center">Loading...</div>;
}
if (error) {
return <div className="text-3xl font-bold text-center">{error}</div>;
}
console.log(pokemons);
return (
<div className="container mx-auto py-10">
<h1 className="text-3xl font-bold text-center">Pokemon List</h1>
<ul className="mx-auto text-center">
{pokemons.map((pokemon) => (
<li key={pokemon.name} className="my-2">
{pokemon.name}
</li>
))}
</ul>
</div>
);
}
export default function Root() {
return (
<Provider store={store}>
<App />
</Provider>
);
}
const root = ReactDOM.createRoot(document.getElementById("root"));
root.render(<Root />);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment