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

237
Visualizações
How to destructure into global variables from inner function? (ReactJS)

I have a react functional-based component that needs some pieces of information lat and lng to pass into my Autocomplete component. I am trying to get lat and lng from an inner function but i couldnt. I tried doing

{ lat, lng } = getLatLng(results[0]) 

but it throws some syntax error, so I also tried

lat = getLatLng(results[0].lat)
lng = getLatLng(results[0].lng)

but it doesnt seem to work. This seems like such a simple issue but i cant figure out why. I tried putting the var keyword in front as well but it didnt work, nor did i expect it to. Below is my whole code for the component.

import usePlacesAutocomplete, { getGeocode, getLatLng } from "use-places-autocomplete"
import { useDispatch } from "react-redux";
import { setOrigin, setDestination } from '../../Slices/originDestinationSlice'
import TextField from '@mui/material/TextField';
import Autocomplete from '@mui/material/Autocomplete';

export const StartPlaces = () => {
    const dispatch = useDispatch()
    const { ready, value, setValue, suggestions: { status, data }, clearSuggestions } = usePlacesAutocomplete();

    const handleSelect = async (val, selectedValue) => {
        setValue(val, true);
        // clearSuggestions();
        const results = await getGeocode({ address: val });

        // { lat, lng } = getLatLng(results[0])
        lat = getLatLng(results[0].lat)
        lng = getLatLng(results[0].lng)

    }
    return <>
        <h4>Enter Origin</h4>
        <Autocomplete
            id="free-solo-demo"
            freeSolo
            options={data.map(({ description }) => description)}
            onChange={(event, value) => {
                
                dispatch(setOrigin({
                    coordinates: { lat, lng },
                    name: value
                }))
            }}
            renderInput={(params) => <TextField {...params} label="Origin" onChange={(e) => handleSelect(e.target.value)} placeholder="e.g. Las Vegas" />}
            sx={{ width: 300 }}
        />
    </>
}

Any help would be greatly appreciated. thank you in advance!!

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

0

you should save your lat e lng in a state to use them correctly

try to change your code like this

import usePlacesAutocomplete, { getGeocode, getLatLng } from "use-places-autocomplete"
import React, {useState} from 'react'
import { useDispatch } from "react-redux";
import { setOrigin, setDestination } from '../../Slices/originDestinationSlice'
import TextField from '@mui/material/TextField';
import Autocomplete from '@mui/material/Autocomplete';

export const StartPlaces = () => {
    const dispatch = useDispatch()
    const { ready, value, setValue, suggestions: { status, data }, clearSuggestions } = usePlacesAutocomplete();
    const [lat, setLat] = useState(0)
    const [lng, setLng] = useState(0)
    const handleSelect = async (val, selectedValue) => {
        setValue(val, true);
        // clearSuggestions();
        const results = await getGeocode({ address: val });

        
        const {lat, lng} = getLatLng(results[0])
        setLat(lat)
        setLng(lng)

    }
    return <>
        <h4>Enter Origin</h4>
        <Autocomplete
            id="free-solo-demo"
            freeSolo
            options={data.map(({ description }) => description)}
            onChange={(event, value) => {
                
                dispatch(setOrigin({
                    coordinates: { lat, lng },
                    name: value
                }))
            }}
            renderInput={(params) => <TextField {...params} label="Origin" onChange={(e) => handleSelect(e.target.value)} placeholder="e.g. Las Vegas" />}
            sx={{ width: 300 }}
        />
    </>
}
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