inertia icon indicating copy to clipboard operation
inertia copied to clipboard

Form Being Reset

Open ramonmalcolm10 opened this issue 2 years ago • 3 comments

Version:

  • @inertiajs/react version: 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:

  1. Install react-google-autocomplete library
  2. 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;
  1. Generate a Map API Key in Google Cloud Console and set the apiKey value
  2. 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)
          }
     />
)
  1. Update the name field and then update the address field to simulate the issue

ramonmalcolm10 avatar Oct 17 '23 12:10 ramonmalcolm10

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,
              }))
          }
     />
)

rikoriswandha avatar Feb 28 '24 08:02 rikoriswandha

Any idea @rikoriswandha why it is making a consecutive call on a string field?

ramonmalcolm10 avatar Feb 28 '24 08:02 ramonmalcolm10

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

rikoriswandha avatar Feb 28 '24 08:02 rikoriswandha

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)

derrickreimer avatar Jun 24 '24 14:06 derrickreimer