Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

195
Visualizações
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?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

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,
      }
    })

  }, []);
about 4 years ago · Juan Pablo Isaza Relatório

0

Call the method once, and set it to your state:

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

  }, []);

You can also spread the result if you dont want to repeat all variables:

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

  }, []);
about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda