Home > Blockchain >  React useState without undefined values
React useState without undefined values

Time:02-19

I'm novice with React and the state concept. So I fetch data from my database with axios. I put everything in a state (accomodation) and then I need to catch a field (country) into datas and use it into other function.

I succeed to catch everything but when I try to test it with a 'console.log' it appears that the two first result returns empty/undefined before having a result. Because the fact the two first attempts are empty/undefined, the other function doesn't work.

Anyone could help me please :)

Here are my code :

const { id } = useParams()

  const [accomodation, setAccomodation] = useState('')

  const getAcc = async () => {
    const data = await axios.get(
      `${process.env.REACT_APP_API_URL}api/v1/accomodations/${id}`
    )
    setAccomodation(data.data.data.accomodation)
  }

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

    const country = accomodation.country
    console.log(country)

CodePudding user response:

To go over what is happening here:

  1. const [accomodation, setAccomodation] = useState('') the accomodation object is set to empty string.
  2. useEffect(() => { getAcc() }, []) getAcc() is called upon render.
  3. const country = accomodation.country; console.log(country) we are still waiting for getAcc() to finish, meanwhile, country is set to the 'country' property of an empty string which is underfined. undefined is printed.
  4. setAccomodation(data.data.data.accomodation) getAcc() finally finishes, and accommodation is hopefully set to the object you intended.

What happens now?.. Nothing. Because you have not done anything to act on a state update. So one of the answers already posted here is on the right track. You need to act on the update of accommodation state.

This is how you trigger an effect on state update:

useEffect(() => {
    if (accommodation.country) {
      console.log(accomodation.country);
     }
    }, [accomodation])

Note that this useEffect() will be invoked whenever accommodation changes from its previous state. If the desired effect is not achieved it may be that accommodation is not the object you intended.

CodePudding user response:

Just check accomodation changes in useEffect with dependency.

   useEffect(() => {
        accomodation && console.log(accomodation.country)
    }, [accomodation])
  • Related