Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

My function returns an object. How to set return value to specific key value in React

I have a function in my react code as so…

  const getLatLngFromAddress = async () => {
    try {
      const response = await Geocode.fromAddress(state.address.address1)
      const { lat, lng } = response.results[0].geometry.location;
      return { lat, lng }
    } catch (err) {
      console.log(err.message)
    }
  }

returns an object. I would like to set my state to only a specific key of the object and not the object itself…

  useEffect(async () => {
    setState({
      ...state,
      address: {
        ...state.address,
        lat: await getLatLngFromAddress().lat,
        lng: await getLatLngFromAddress().lng
      }
    })

  }, []);

useEffect above returns undefined. Is there any way to do this?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You need to read the properties from the value resolved from the promise. Currently you are trying to read them from the promise itself and then awaiting those undefined values.

lat: (await getLatLngFromAddress()).lat,

However, you are calling getLatLngFromAddress twice. Store the values in variables and then reuse them instead.

  useEffect(async () => {
    const latlng = await getLatLngFromAddress()
    setState({
      ...state,
      address: {
        ...state.address,
        ...latlng,
      }
    })

  }, []);
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading