Welcome back! From the previous post we are going to be discussing the FavouritesModal and how it differs from the PokemonModal when in reality they look indentical.
The problem
As was previously mentioned, I couldn't simply use the same component in the same way as this page was fetching the data from the json server rather than the API.
Now I'm sure there's a way to incorporate both so that you are saving just the pokemon's name in the backend and then you can fetch the relevant data from the API, however I couldn't figure that out and I was pulling out my hair at the best of times.
So to get around that, all of the data that was being rendered on the modal I decided to pass to the json server so that we could simply get that data and render it on a new component.
The code
Here is the code for the FavouritesModal.jsx
How it works:
- Import statements
- Functional component declaration for pokemon, closeModal function, favourites and updateFavourites
- Type color mapping that maps pokemon types to specific colours
- Set default background colour to gray again if a type can’t be identified
- useState hook to create a piece of state (isInFavourites) and a function (setIsInFavourites) to manage whether the current Pokemon is in the user's favourites
- useEffect hook checks whether the current Pokemon is in the user's favorites and updates the state accordingly whenever the favourites array or the pokemon.id changes
- handleFavourites function is responsible for handling the addition or removal of a Pokemon from the user's favorites. It uses the fetch function to communicate with a server. If the Pokemon is already in the favorites, it removes it; otherwise, it adds it
- JSX structure for the modal component
- Export statement
Closing remarks
So that's the favourites modal for ya. Again I'm sure there's a more efficient way to do this so that you don't need a separate component but I found this method the easiest for myself!
Top comments (0)