TL;DR: My React components doesn’t rerender after a remix.run ActionFunction.
I have a route with a form in which, when submitted, runs an ActionFunction. The ActionFunction then does something and returns, e.g., return json({ message: "Success!", status: 200 });
.
I want to show the returned data in a React component, e.g. like this:
const submitResponse = useActionData();
return (
<Page narrowWidth title="Opret produkt">
<Card>
<h1>{submitResponse?.message ? submitResponse.message : "No Message"}</h1>
</Card>
</Page>
)
To begin with, the submitResponse variable is undefined, so the h1 shows "No Message". This is expected.
Then, after the ActionFunction, it should contain the json object and thus rerender the h1. Unfortunately, it doesn’t. It always just says "No Message."
I understand that we’re not changing any state here, but there is an example of this in the remix.run docs here where it rerenders, so it should work.
Unfortunately, the h1 never rerenders. It always just says "No Message", and I can’t figure out why.
2
Answers
From React Remix docs, they have shown that useActionData() hook requires a form JSX element to wrap the whole component you are working on.
You can try to rewrite the code like that:
Let’s discuss this,
The problem here is, that you are returning an object as a json format which is not an inbuild function or object in react. Insted you can use JSON. Also you can return JSON object with stringify method as below.
Later, when displaying the message, we use JSON.parse to convert the JSON string back to a JavaScript object and retrieve the message property.