Home > other >  State in useEffect undefined after the useEffect sets the state?
State in useEffect undefined after the useEffect sets the state?

Time:05-06

I have a React Native app in which I am running some code that looks like the code below. Why is the following output undefined? Reading someState from useEffect is undefined even when the state is set inside the useEffect

const SomeComponent = () => {
  const [someState,setSomeState] = useState();
  
  const anFunction = () => {
    let data = 'data'
    return data
  }

  useEffect(() => {
    const theData = anFunction();
    setSomeState(theData)
    console.log(someState)
  },[])

  ...

  // later renders some component
}

I am attempting set the state and then read the state within this useEffect because I would like to implement something like:

  const doSomethingWithTheData = () => {
    //some transformation here
    setSomeState(transformedData)
  }

  useEffect(() => {
    const theData = anFunction();
    setSomeState(theData)
    
    doSomethingWithTheState()

  },[])

CodePudding user response:

It should work by adding a .then

.then(doSomethingWithTheState())

CodePudding user response:

It is undefined because useEffect is not async. Your initial state is already undefined so you see undefined in console.log. To create async logic inside useEffect you should update like this

useEffect(() => {
    async function test(){
      //Your logic here
    } 
    test()

  },[])

CodePudding user response:

You might get something out of my answer to a similar question here: React Native I can not store an array with AsyncStorage

Setting state is neither sync nor async. It's a quirk of the React ecosystem. If you need to work with the state directly after it's been changed, do it in a useEffect with the state variable in the dependency array.

  • Related