jaredpalmer / formik

Build forms in React, without the tears 😭
https://formik.org
Apache License 2.0
34.02k stars 2.79k forks source link

useState in parent component not keep state, when parent component's callback function is called from child component with useField #3716

Open Lelouch-666 opened 1 year ago

Lelouch-666 commented 1 year ago

Bug report

Current Behavior

formik values are not kept when a call back function is called in child component that's created with Formik useField.

Here is the code: https://nv1m89.csb.app. As shown in below screenshot,console.log in handleStoreLocationUpdate function shows that the form values are not kept after callback function is called from child component.

Alt Text

Expected behavior

form values should be kept

Reproducible example

https://nv1m89.csb.app/

Suggested solution(s)

Additional context

https://stackoverflow.com/questions/75330636/usestate-in-parent-component-not-keep-state-when-parent-components-callback-fu

Your environment

{
  "name": "react",
  "version": "1.0.0",
  "description": "React example starter project",
  "keywords": [
    "react",
    "starter"
  ],
  "main": "src/index.js",
  "dependencies": {
    "@googlemaps/js-api-loader": "1.15.1",
    "formik": "2.2.9",
    "google-map-react": "2.2.0",
    "react": "18.2.0",
    "react-dom": "18.2.0",
    "react-scripts": "4.0.0"
  },
  "devDependencies": {
    "@babel/runtime": "7.13.8",
    "typescript": "4.1.3"
  },
  "scripts": {
    "start": "react-scripts start",
    "build": "react-scripts build",
    "test": "react-scripts test --env=jsdom",
    "eject": "react-scripts eject"
  },
  "browserslist": [
    ">0.2%",
    "not dead",
    "not ie <= 11",
    "not op_mini all"
  ]
}
shehabadel commented 1 year ago

I am currently facing the same bug; I am not sure if it is related to the current version of Formik?

Lelouch-666 commented 1 year ago

I have switched to https://react-hook-form.com which doesn't have this issue.

olzhas-kalikhan commented 1 year ago

I don't think it's a bug, your onPlaceChange fn reference never changed since it's in useEffect without any dependencies. It get first onPlaceChange reference that uses empty formValues and formik,values

You can something like this:

 const [field, meta, formikHelpers] = useField(props);
 .....
 const onPlaceChanged = () => {
    const place: window.google.maps.places.PlaceResult = autoCompleteInstanceRef.current.getPlace();
    if (!place) return;
    console.log(place.formatted_address);
    formikHelpers.setValue(place.formatted_address);
  };

  React.useEffect(() => {
    if (field.value) onAddressUpdate(field.value);
  }, [field.value,onAddressUpdate]);