Home > OS >  useState not running quick enough for fetch request
useState not running quick enough for fetch request

Time:11-21

I would like to fetch a "board_ID": fetch("http://localhost:4000/NewGame") and then use that board_ID in the address of the following fetch: fetch("http://localhost:4000/Turn/" board_ID). The problem is that setboard_ID (initialized previously with useState) does not update the board_ID quick enough so there is an error in the fetch for the "Turn." What is the best way to solve this problem?

useEffect(() => {
   if (didFetch == false) {
   fetch("http://localhost:4000/NewGame")
     .then(res => res.text())
     .then(
       (result) =>{
           console.log(result)
           **setboard_ID(result)**
       },
       (error) => {
           setisLoaded(true)
           seterror(error)
       }
     )
   }
 })

 useEffect(() => {
   if (getplayer == true){
     console.log("http://localhost:4000/Turn/"   board_ID)
     **fetch("http://localhost:4000/Turn/"   board_ID)**
     .then(res => res.text())
     .then(
       (result) =>{
           console.log(result)
           player = result
           setGetplayer(false)
       },
       (error) => {
           seterror(error)
       }
     )
   }
 })

CodePudding user response:

You can try running useEffect with dependency to that state. Works like that:

useEffect(function, [dependency]) 

Then, first useEffect will run and update the state launching the second one

CodePudding user response:

Add to the second useEffect the board_ID in the dependency array [board_ID].

The useEffect hook allows you to perform side effects in a functional component. There is a dependency array to control when the effect should run. It runs when the component is mounted and when it is re-rendered while a dependency of the useEffect has changed

CodePudding user response:

I'm not sure why your useEffects does not have a dependency array (it's dangerous) as it will call the lifecycle methods repeatedly, which will re-render UI/App many times due to which App may crash. Plus I don't see any check for the existence of board_ID for the second useEffect.

Adding board_ID in dependency array should fix part of the issue.

SUDO :

 useEffect(() => {
 if (getplayer && board_ID !='' ){  // == true is redundant and board_ID != <your initial state means it has some valid value>
 console.log("http://localhost:4000/Turn/"   board_ID)
 **fetch("http://localhost:4000/Turn/"   board_ID)**
 .then(res => res.text())
 .then(
   (result) =>{
       console.log(result)
       player = result
       setGetplayer(false)
   },
   (error) => {
       seterror(error)
   }
  )
 }
},[board_ID])
  • Related