From 2d4426d84d5f09d9076860bad0b8120c769ea921 Mon Sep 17 00:00:00 2001 From: Jason Zhu Date: Mon, 17 Apr 2023 00:10:26 +1000 Subject: [PATCH] Remove setPokemonList action, and replaced calling pokedexApi using regular fetch --- src/features/Pokedex/pokedexSlice.ts | 28 +++++++++++++++------------- 1 file changed, 15 insertions(+), 13 deletions(-) diff --git a/src/features/Pokedex/pokedexSlice.ts b/src/features/Pokedex/pokedexSlice.ts index 56e4929..6b4fda6 100644 --- a/src/features/Pokedex/pokedexSlice.ts +++ b/src/features/Pokedex/pokedexSlice.ts @@ -24,18 +24,26 @@ export const fetchPokemonsInTheRegion = createAsyncThunk< { length: endId - startId + 1 }, (_, i) => i + startId, ); - // use pokemonIds to fetch pokemon data using getPokemonQuery and store in state - const pokemonList = await Promise.all( + // use pokemonIds to fetch pokemon data using fetch, remember to clear all fetched cache after saving data into store + const pokemonList: PokemonResponseData[] = await Promise.all( pokemonIds.map( id => - dispatch(pokedexApi.endpoints.getPokemon.initiate(id)) as Promise<{ - data: PokemonResponseData; - }>, + fetch(`https://pokeapi.co/api/v2/pokemon/${id}`).then(res => + res.json(), + ) as Promise, ), ); - const pokemonListData = pokemonList.map( - (pokemon: { data: PokemonResponseData }) => pokemon.data, + + const pokemonListData: PokemonResponseData[] = pokemonList.map( + (pokemon: PokemonResponseData) => pokemon, ); + + // clear all fetched data cache + // pokemonIds.forEach(id => { + // const cacheKey = `https://pokeapi.co/api/v2/pokemon/${id}`; + // delete (window as any).fetch.cache[cacheKey]; + // }); + return pokemonListData; }); @@ -56,8 +64,6 @@ export const pokedexSlice: Slice = createSlice({ reducers: { setSelectedRegion: (state, action: PayloadAction) => { state.selectedRegion = action.payload; - // call fetchPokemonsInTheRegion - fetchPokemonsInTheRegion(action.payload); }, setSelectedType: (state, action: PayloadAction) => { state.selectedType = action.payload; @@ -80,9 +86,6 @@ export const pokedexSlice: Slice = createSlice({ setIsLoadingPokemons: (state, action: PayloadAction) => { state.isLoadingPokemons = action.payload; }, - setPokemonList: (state, action: PayloadAction) => { - state.pokemonList = action.payload; - }, }, extraReducers: builder => { // add fetchPokemonsInTheRegion @@ -111,7 +114,6 @@ export const { setRegionOptions, setTypeOptions, setSortOptions, - setPokemonList, } = pokedexSlice.actions; export default pokedexSlice.reducer;