0

i have a problem to get my state value.

i have declared my state homeworks

const [homeworks, setHomeworks] = useState([])

I call a function in my useEffect

useEffect(()=>{
    fetchHomeworks()
},[])

This function call a service for get data from my API. And when data loading i set my states and i load other function with state but i don't get state in my function initMercure()

const fetchHomeworks = async () => {
    try {
        let data
        if (classroom_id === "all") {
            data = await homeworksAPI.findAll()
        } else {
            data = await classroomsAPI.getHomeworks(classroom_id)
        }
        await setHomeworks(data)
        await initMercure()
    } catch (error) {
        console.log(error)
    }
}
const initMercure = async () => {
    console.log("homeworks (initMercure): ", homeworks) // <--- HERE, i have array blank []
}

I have try it but don't work

await setHomeworks(data, initMercure())

and

useEffect(()=>{
    fetchHomeworks()
    initMercure()
},[])

[RESOLVED]

useEffect(()=>{
        fetchHomeworks()
        fetchClassroom()
    },[classroom_id])

useEffect(()=>{
   if (homeworks.length>0) initMercure();
},[homeworks])

Thank you <3

ThomasM
  • 67
  • 1
  • 6
  • It appears to me that component (which suppose to render the received items from the API) isn't ready yet. I also believe you need to have a look at the `Suspense` in the latest ReactJS version. More info on this: https://blog.logrocket.com/async-rendering-in-react-with-suspense-5d0eaac886c8/#:~:text=What%20is%20React%20Suspense%3F%20Suspense%20is%20a%20new,in%20regard%20to%20CPU%20power%20and%20data%20fetching. – Malakai Aug 09 '21 at 14:27
  • 1
    The code works just fine, you're simply expecting state to be updated before it is. If you want `initMercure` to have the value from `data` then either pass it that value or call `initMercure` in a `useEffect` which monitors that value. – David Aug 09 '21 at 14:28
  • This might help answering your question: https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous – Ryan Le Aug 09 '21 at 14:29
  • `seHomeworks` doesn't return a _promise_, so _await_ is useless with it. It also doesn't use any callback argument like `this.setState` does, so, like [David said](https://stackoverflow.com/questions/68713719/await-state-loading-react?noredirect=1#comment121435972_68713719), you'd need to use `useEffect(() => { if (homeworks) initMercure(); }, [homeworks])` – Emile Bergeron Aug 09 '21 at 14:42
  • Note that you can have multiple `useEffect` in a component. – Emile Bergeron Aug 09 '21 at 14:43

0 Answers0