0

I have integrated google map auto-completed, it's working well, even i have console logged, every data is appearing as expected but the problem is, when i select, it doesn't update the state

Here you go for my component

import Autocomplete from "react-google-autocomplete";

const TestForm = () => {
    const [profile, setProfile] = useState({});

    const onPlaceSelected = (place) => {
      console.log(place)
      setProfile({...profile, "test": "test"})
      console.log(profile, )
    };

    const handleProfileChange = (e) => {
        setProfile({...profile, [e.target.name]: e.target.value})
      };

  
  return (
    <>
      
    <input onChange={handleProfileChange} type="text"></input>

    <Autocomplete
        apiKey="apikey"
        defaultValue={formData.profile.location || ""}
        onPlaceSelected={onPlaceSelected}
        />
                            
    </>
  );
};

You may notice, i used two different method to update state, one for general input fields and another for autocomplete lib, but general input field state is updateing but autocomplete state is not updating, i have console logged the place, i see it is appearing, only problem is when i select a location, the selected location doesnt add my state, what is the issue? why it's behaving so weirds? can anyone help me?

1 Answer 1

1

You cant log the state right after you updated it, because it's async. Try logging the state change in useEffect hook

const [profile, setProfile] = useState({});

const onPlaceSelected = (place) => {
  console.log(place)
  setProfile({...profile, "test": "test"})
};

useEffect(() => { console.log(profile) }, [profile])
Sign up to request clarification or add additional context in comments.

2 Comments

Hey, it works but other state is being reset now,
It's because onPlaceSelected overwrites, the state right after onPlaceSelected, with the old state, when you do { ...profile } which does not contain changes from onPlaceSelected state change. I would suggest keep two separate states, and if you need - handle them with useEffect

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.