How I Solved My React-Admin Form State Reset Issue

The Problem

Recently, while working on a project using React-Admin, I encountered a frustrating issue. I had an Edit component with a TabbedForm set to pessimistic mode, and a custom data provider based on React-Admin’s simple REST provider. Everything worked fine until the server-side validation kicked in.

The validation rule was straightforward: it ensured that no two entities shared the same name. If the rule was violated, the server would correctly return a 400 error with a message, which I displayed in a toast notification. However, this is where the problem arose. Every time the server returned a 400 error, the entire form state would reset, wiping out all the progress the user had made. This was not only annoying but also a poor user experience.

The Investigation

I noticed that after the 400 error response, there was an additional HTTP request sent to the API to fetch the entity by ID again. This was the getOne method on the data provider being called, which resulted in the form being reset to its initial state.

The question was: how could I prevent the form state from being reset after a 400 response from the server?

The Solution

After some digging and experimenting, I found a solution that worked perfectly. The key was to override the onFailure behaviour of the form submission. Here’s the custom onFailure function I implemented:

const onFailure = (error: any) => {
    notify(
      typeof error === "string"
        ? error
        : error.message || "ra.notification.http_error",
      { type: "warning" }
    );
    // Avoiding the default refresh behavior via refresh()
  };

By doing this, I effectively stopped the form from refreshing and losing its state upon encountering a 400 error.

Why This Works

The onFailure callback is part of React-Admin’s CreateEdit component. By default, it performs certain actions when a submission fails, including refreshing the page. By customising this behaviour, I could keep the existing form state intact, even when the server responded with an error.

Reference

For those interested in the technical details or who might be facing a similar issue, you can find more information in the React-Admin documentation here: React-Admin CreateEdit documentation.

Conclusion

In the end, the solution was a simple tweak to the onFailure callback. I hope sharing my experience can help someone else facing a similar challenge.