inertia
inertia copied to clipboard
Form Being Reset
Version:
@inertiajs/reactversion: 1.0.12
Describe the problem:
useForm keeping resetting when I update a specific field from a component that utilize react-google-autocomplete library.
Steps to reproduce:
- Install
react-google-autocompletelibrary - Create custom input
import { usePlacesWidget } from "react-google-autocomplete";
import * as React from "react";
type Props = {
onChanged: (address: string) => void;
value: string;
};
const LocationInput: React.FC<Props> = ({
onChanged,
value,
}) => {
const { ref } = usePlacesWidget<HTMLInputElement>({
apiKey: import.meta.env.VITE_GOOGLE_MAP_KEY,
onPlaceSelected: (place) => onChanged(place.formatted_address ?? ""),
options: {
fields: ["geometry", "formatted_address", "url", "vicinity"],
types: ["address"],
},
});
return (
<input
ref={ref}
defaultValue={value}
/>
);
};
export default LocationInput;
- Generate a Map API Key in Google Cloud Console and set the
apiKeyvalue - Create parent component and add a new form that utilize the component
const form = useForm({
name: "",
address: "",
});
return (
<input value={form.data.name} onChanged={(e) => form.setData("name", e.target.value)} />
<LocationInput
value={form.data.address}
onChanged={(e) =>
form.setData("address", e)
}
/>
)
- Update the name field and then update the address field to simulate the issue
I experienced this issue recently today. Fixed by setting the data according to this #1086. So you can try this:
const form = useForm({
name: "",
address: "",
});
return (
<input value={form.data.name} onChanged={(e) => form.setData("name", e.target.value)} />
<LocationInput
value={form.data.address}
onChanged={(e) =>
form.setData((data) => ({
...data,
address: e,
}))
}
/>
)
Any idea @rikoriswandha why it is making a consecutive call on a string field?
I have no idea, in my case, I'm using filepond-react and it keeps resetting the other fields' state. Probably related to the internal state of the library
We are now using an updater function internally with setData, so consecutive calls to set data should work as expected when the next release is cut (#1859)