Mickael Muller
Mickael Muller

Reputation: 210

How to use useFormState outside a <Form/>

I upgraded react-admin v2.0 to 3.0, i followed this guide.

I have a problem with react-final-form and a jest test.

I did a custom logic on a button and I need the form values, so I use the useFormState from react-final-form. It works fine on the application but I have an error while running the jest test.

Here is my code in my component

import { Button } from '@material-ui/core';
import { Save } from '@material-ui/icons';
import { useFormState } from 'react-final-form';
import React, { useCallback } from 'react';

const Toolbar = ({ onSubmit, translate }) => {
  const formState = useFormState();

  const handleCustomSubmit = useCallback(() => {
    const data = formState.values;
    onSubmit(data);
  }, [formState.values]);

  return (
    <Button id="SLM_saveButton" onClick={handleCustomSubmit}>
      <Save />
      {translate('ui_update')}
    </Button>
  );
};

And here the error

useFormState must be used inside of a <Form> component

       6 |
       7 | const Toolbar = ({ onSubmit, translate }) => {
    >  8 |   const formState = useFormState();
         |                     ^
       9 |
      10 |   const handleCustomSubmit = useCallback(() => {
      11 |     const data = formState.values;

      at useForm (node_modules/react-final-form/dist/react-final-form.cjs.js:297:11)
      at useFormState (node_modules/react-final-form/dist/react-final-form.cjs.js:309:14)
      at Component (packages/ui/src/components/Toolbar/component.js:8:21)
      at wrappedComponent.displayName.adapter.displayNameOfNode.type (node_modules/enzyme-adapter-react-16/src/ReactSixteenAdapter.js:569:33)
      at ReactShallowRenderer.render (node_modules/react-test-renderer/cjs/react-test-renderer-shallow.development.js:858:32)
      at fn (node_modules/enzyme-adapter-react-16/src/ReactSixteenAdapter.js:645:55)
      at withSetStateAllowed (node_modules/enzyme-adapter-utils/src/Utils.js:99:18)
      at Object.render (node_modules/enzyme-adapter-react-16/src/ReactSixteenAdapter.js:645:20)
      at new ShallowWrapper (node_modules/enzyme/src/ShallowWrapper.js:411:22)
      at Object.shallow (node_modules/enzyme/src/shallow.js:10:10)

I don't understand how to use the <Form/> and the useFormState correctly in react-admin

Upvotes: 0

Views: 6186

Answers (1)

Erik R.
Erik R.

Reputation: 7272

You need to put a <Form> around your <Toolbar/> in your test. useFormState() looks in the React context for the containing form. Apparently in your application, your <Toolbar/> is always inside a <Form/>, so you need to replicate that for the test.

Upvotes: 2

Related Questions