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?