Replace fetch in fetchPokemonsInTheRegion by using RTK Query
parent
6f04c341e3
commit
3996e09308
|
@ -1,10 +1,11 @@
|
||||||
|
import type { PayloadAction, Slice } from '@reduxjs/toolkit';
|
||||||
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
|
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
|
||||||
import type { Slice, PayloadAction } from '@reduxjs/toolkit';
|
|
||||||
|
|
||||||
import { PokedexStateProps } from 'features/Pokedex/types/slice';
|
import { PokedexStateProps } from 'features/Pokedex/types/slice';
|
||||||
|
|
||||||
import { getStartAndEndIdsForRegion } from './utils';
|
import { getStartAndEndIdsForRegion } from './utils';
|
||||||
import { PokemonResponseData } from 'types/api';
|
import { PokemonResponseData } from 'types/api';
|
||||||
|
import { pokeApi } from 'app/services/pokeApi';
|
||||||
import { RootState } from 'app/store';
|
import { RootState } from 'app/store';
|
||||||
|
|
||||||
export const fetchPokemonsInTheRegion = createAsyncThunk<
|
export const fetchPokemonsInTheRegion = createAsyncThunk<
|
||||||
|
@ -22,21 +23,14 @@ export const fetchPokemonsInTheRegion = createAsyncThunk<
|
||||||
{ length: endId - startId + 1 },
|
{ length: endId - startId + 1 },
|
||||||
(_, i) => i + startId,
|
(_, i) => i + startId,
|
||||||
);
|
);
|
||||||
// use pokemonIds to fetch pokemon data using fetch, which won't save the data in the cache
|
|
||||||
const pokemonList = await Promise.all(
|
const pokemonList = pokemonIds.map(id =>
|
||||||
pokemonIds.map(
|
dispatch(pokeApi.endpoints.getPokemon.initiate(id))
|
||||||
id =>
|
.unwrap()
|
||||||
fetch(`https://pokeapi.co/api/v2/pokemon/${id}`).then(res =>
|
.then(data => data),
|
||||||
res.json(),
|
|
||||||
) as Promise<PokemonResponseData>,
|
|
||||||
),
|
|
||||||
);
|
);
|
||||||
|
|
||||||
const pokemonListData = pokemonList.map(
|
return await Promise.all(pokemonList);
|
||||||
(pokemon: PokemonResponseData) => pokemon,
|
|
||||||
);
|
|
||||||
|
|
||||||
return pokemonListData;
|
|
||||||
});
|
});
|
||||||
|
|
||||||
export const initialState: PokedexStateProps = {
|
export const initialState: PokedexStateProps = {
|
||||||
|
|
Loading…
Reference in New Issue