0

I have a useState object in my react app that looks like this:

const [data, setData] = useState({
    soverview: "",
    address: "",
    first_name: "",
    last_name: "",
    email: "",
    phone: "",
    dob: ""
});

Throughout my application I have a form and each input has onChange={handleChange}.

const handleChange = ({ currentTarget: input }) => {
    setData({ ...data, [input.name]: input.value });
};

However, I also have a google autocomplete field that allows users to type in their address and have it autofilled out. For that <Autocomplete/> field, I have set onPlaceSelected={(place) => {handleAddress(place)}}.

function handleAddress(place) {
    setData({ ...data, address: place.formatted_address });
}

Here is some of my jsx form:

<textarea
    className="mb-15"
    name="soverview"
    onChange={handleChange}
    value={data.soverview}
></textarea>

<Autocomplete
    className="mb-30"
    placeholder="Start typing your address"
    apiKey={api_key}
    options={{
        types: ["geocode"],
        componentRestrictions: { country: "aus" },
    }}
    onPlaceSelected={(place) => {
        handleAddress(place)
    }}
/>

<input
    className="mb-15 field-hl p-10-5"
    type="text"
    name="first_name"
    placeholder="John"
    onChange={handleChange}
    value={data.first_name}
    required
/>

However, the ...data does not seem to be working as it clears the soverview field which is set initially, and then keeps all the data from address onwards. Why is this happening?

sfhasfasf
  • 55
  • 5
  • 1
    How do you know the `soverview` field is cleared? It's initially an empty string anyway. – Unmitigated Feb 13 '23 at 23:46
  • 2
    Did you tried `setData(prev => ({ ...data, address: place.formatted_address })); ` – devpolo Feb 13 '23 at 23:48
  • Could the address auto-complete field feature be accidentally triggering a page/form refresh? – esinator Feb 14 '23 at 00:07
  • Maybe....? I am using `react-google-autocomplete` @esinator – sfhasfasf Feb 14 '23 at 00:09
  • @Unmitigated because the soverview field is before the address field. So `onChange` it is setting the value to `data`. Then once the address is set, it seems to clear the soverview field. – sfhasfasf Feb 14 '23 at 00:10
  • Can you add a little bit of your JSX so we can see how you structured the form components? – esinator Feb 14 '23 at 00:15
  • @esinator done! As you can see there are 3 inputs. I tried logging `form` after each change. It seems to be saving `soverview`, but removing it after `address` is updated. After the last input is done, `data` contains everything but `soverview`. – sfhasfasf Feb 14 '23 at 00:20
  • 3
    @devpolo that should be `setData(prev => ({ ...prev, address: place.formatted_address }))`. See https://reactjs.org/docs/hooks-reference.html#functional-updates – Phil Feb 14 '23 at 00:26
  • @Phil is right! That fixes it – esinator Feb 14 '23 at 00:30

0 Answers0