Issues with state-changes in submit method of AtlasKit Form

255 Views Asked by At

In the submit method of an Atlaskit Form, I want to change a value of a state property that results in the form being hidden:

<Form onSubmit={data => {
    return new Promise(resolve => {
        setShowForm(false);
        resolve();
    })
  }}>
</Form>

However, this results in a React error:

Can't perform a React state update on an unmounted component. This is a no-op, but it indicates a memory leak in your application. To fix, cancel all subscriptions and asynchronous tasks in the componentWillUnmount method.

The error disappears when i set that value a little later:

setTimeout(() => setShowForm(false));

So apparently the form is still unmounting while i change state (although i don't know why that should affect on the form, but i am not too familiar with React yet). What is the approach i should be taking here?

1

There are 1 best solutions below

1
On

This is because you made an asynchronous request to an API, the request (e.g. Promise) isn’t resolved yet, but you unmount the component.

You can resolve this issue by maintaining a flag say _isMounted to see if component is unmounted or not and change the flag value based on promise resolution.

// Example code

class Form extends Component {
  _isMounted = false;

  constructor(props) {
    super(props);

    this.state = {
      data: [],
    };
  }

  componentDidMount() {
    this._isMounted = true;

    axios
      .get('my_api_url')
      .then(result => {
        if (this._isMounted) {
          this.setState({
            data: result.data.data,
          });
        }
      });
  }

  componentWillUnmount() {
    this._isMounted = false;
  }

  render() {
    ...
  }
}