-1
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?

moaksan
  • 13
  • 2

1 Answers1

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]}
Muhammad Umar
  • 1,291
  • 7
  • 13
  • If this is the answer, the question is an **often-repeated** duplicate and should be closed as such. Please don't post answers to obvious duplicates. – T.J. Crowder Jun 01 '22 at 10:31