Advertisement
Guest User

pokemonDataContext

a guest
Apr 23rd, 2020
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.01 KB | None | 0 0
  1. import React, { createContext, useReducer, useEffect, useState } from 'react';
  2. import axios from 'axios';
  3.  
  4. import {
  5. GET_POKEMON_LIST,
  6. SET_POKEMON_LIST,
  7. SET_POKEMON_LIST_SUCCESS,
  8. initialPokemonListState,
  9. pokemonListReducer,
  10. } from '../reducers/pokemonListReducer';
  11.  
  12. export const PokemonDataContext = createContext();
  13.  
  14. const PokemonDataProvider = (props) => {
  15. const [pokemonList, dispatch] = useReducer(pokemonListReducer, initialPokemonListState);
  16.  
  17. useEffect(() => {
  18. const fetchData = async () => {
  19. dispatch({ type: GET_POKEMON_LIST })
  20. try{
  21. const result = await axios(pokemonList.pokeListUrl);
  22. dispatch({ type: SET_POKEMON_LIST_SUCCESS, payload: result.data });
  23. } catch (err) {
  24. dispatch({ type: SET_POKEMON_LIST });
  25. }
  26. }
  27.  
  28. fetchData();
  29. }, []);
  30.  
  31. return (
  32. <PokemonDataContext.Provider value={{ ...pokemonList, dispatch }}>
  33. {props.children}
  34. </PokemonDataContext.Provider>
  35. )
  36. }
  37.  
  38. export default PokemonDataProvider;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement