Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

267
Visualizações
async/await seems to not work well in my function
const initialState={
  isLogin: false,
  userInfo: null,
}

function App() {
  const [state, setState]= useState(initialState)

  useEffect(()=>{
    async function fetchUserInfo(){
      await initializeUserInfo({state, setState}) // here is the problem
      console.log(state)
    }
    fetchUserInfo()
  }, [])
}

export async function initializeUserInfo({state, setState}){
  let cacheName='writinghelper'
  
  try{
    const cache= await caches.open(cacheName)
    const isLogin= await cache.match('isLogin')
    
    if(isLogin){
      
      if(await isLogin.json()){
        const userInfo= await (await cache.match('userInfo')).json()
        await setState({
          ...state,
          isLogin:true,
          userInfo: userInfo
        })
        
      } else{
        await setState({
          ...state,
          isLogin:false,
          userInfo: null
        })
      }
    } else{
      cache.put('isLogin', new Response(false))
      cache.put('userInfo', new Response(null))
      cache.put('data', new Response(null))
    }
  } catch(e){
    console.log(e.message)
  }
}

I made 'initializeUserInfo' function and use it in 'useEffect' hook. I used async/await in 'useEffect', so I expected the variable 'state.isLogin' would be changed to 'true' and print 'true' at console.log(state). But console.log print 'false' over and over. What is the problem?

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You will never see useState throwing the updated state in the very next line you update the state in. Create a useEffect for your 'state' and console.log(state) there. If your function is returning true, you will surely see setState.isLogin to true

useEffect(()=>{console.log(state)},[state]}
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda