Skip to content

FormSpy - Cannot update a component while rendering a different component #809

Open
@ThaNarie

Description

@ThaNarie

Are you submitting a bug report or a feature request?

bug report

What is the current behavior?

When using FormSpy, the onChange is called during rendering, and throws an error if you use setState.

<FormSpy
  subscription={{ values: true }}
  onChange={change => {
    // fired during rendering, calling a `useState` setter fails
    setValues(change.values);
  }}
/>
Warning: Cannot update a component (`App`) while rendering a different component (`FormSpy`). To locate the bad setState() call inside `FormSpy`, follow the stack trace as described in https://fb.me/setstate-in-render
    in FormSpy (at App.js:23)
    in form (at App.js:13)
    in ReactFinalForm (at App.js:10)
    in App (at src/index.js:9)
    in StrictMode (at src/index.js:8)

What is the expected behavior?

No error.

Sandbox Link

https://codesandbox.io/s/react-final-form-formspy-hltnv?file=/src/App.js

What's your environment?

    "final-form": "4.20.0",
    "react": "16.13.1",
    "react-dom": "16.13.1",
    "react-final-form": "6.5.0",

Other information

The issue seems to be that onChange in the useFormState is called in the useState init function, which means during rendering:

onChange(initialState)

This is part of a range of error messages introduced in react 16.13, and related to an existing issue (#751)

A workaround would be to put any setState on the onChange in a setTimeout(... ,0), but this feels like a hack, and not clear to new users.

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions