简体   繁体   中英

Can't get context values on NextJS

I'm trying to get values from context api, but, i getting an default value (without the updates made during the context call) and a undefined value (that is supposed to get a value in the context provider)

sortListContext.tsx

import React from 'react'
type Props = {
    actualSort?:string;
    sorts:string[];
}
export const SortListContext = React.createContext<Props>({
    sorts: []
})

export function SortListProvider({children}:any){
    const [actualSort, setActualSort] = React.useState<string>()
    const sorts = ['numberAsc','numberDesc','nameAsc','nameDesc']

    function getSort(){
        if(typeof window !== 'undefined'){
            const local = localStorage.getItem('sort')
            if(local){
                return ('A')
            }
            else{
                return ('B')
            }
          }
    }

    React.useEffect(()=>{
        setActualSort(getSort)
    },[])
    
    return (
        <SortListContext.Provider value={{ sorts, actualSort}}> 
            {children}
        </SortListContext.Provider>
    )


}

export function useSortListContext(){
    return React.useContext(SortListContext)
}

favorites.tsx

import React from 'react'
import  Container  from '../components/pokedex/container/'
import  Main  from '../components/pokedex/main/'
import  PokemonList  from '../components/pokedex/pokemonList/'
import {useFavoritesContext} from '../contexts/favoritesContext'
import {useSortListContext} from '../contexts/sortListContext'

interface Types  {
  type: {
    name:string;
  }
}

interface PokemonProps {
  id:number;
  name:string;
  types: Types[];
}


const Favorites = () => {
    const {favorites} = useFavoritesContext()
    const {sorts, actualSort} = useSortListContext()

    const [localFavorites, setLocalFavorites] = React.useState<string[]>()
    const [pokemonList, setPokemonList] = React.useState<PokemonProps[]>([])


    React.useEffect(()=>{
      if(typeof window !== 'undefined'){
        console.log(actualSort, sorts)
      }
      

    },[actualSort, sorts])

    React.useEffect(()=>{
      if(localFavorites && localFavorites.length > 0){
          
          localFavorites?.forEach((item)=>{
            async function getPokemon() {
              const response = await fetch(`https://pokeapi.co/api/v2/pokemon/${item}`) 
              const data = await response.json()
    
              setPokemonList((oldPokemonList)=> [...oldPokemonList, data])
              
              
            }
            getPokemon()
            
          })
      }
        
    },[localFavorites])

    React.useEffect(()=>{
      setLocalFavorites(favorites)
      setPokemonList([])
    }, [favorites])

    
      return (
      <Container>
       <Main>
        <PokemonList pokemonList={pokemonList} /> 
       </Main>
       </Container>
      )
    
    
  
}

export default Favorites

i've already tried put an initial value to actualSort but doesn't work, the error probably is on the provider

i just forgot wrapping my app with the provider, thanks yousoumar, that's my first project using Context.

here is the code fixed _app.tsx

import type { AppProps } from 'next/app'
import GlobalStyle from '../styles/global'

import {FavoritesProvider} from '../contexts/favoritesContext'
import {SortListProvider} from '../contexts/sortListContext'

export default function App({ Component, pageProps }: AppProps) {
return (
<>
<GlobalStyle />

<FavoritesProvider>
<SortListProvider>
  <Component {...pageProps} />
</SortListProvider>
</FavoritesProvider>
 
</>)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM