I am using react-router-dom@6.11.2 and have several pages. User navigates from one page to another. The second page contains a pure functional form component that has both a react-router loader() and a submission action(). User fills out the form, clicks save, the action() function is called which saves the data to API, and then returns redirect("..") to navigate back to the previous page, but what React Router does is navigate back to the main page "/" instead.
In their API documentation on redirect() it does not say how to navigate back, only forwards:
https://reactrouter.com/en/main/fetch/redirect
Here is a simplified version of my form's action() function.
/** submit POST for add/update */
export async function action({ request, params }) {
const formData = await request.formData();
const updates = Object.fromEntries(formData);
// call API, blah blah
return redirect("..");
}
What is the official way to handle this?
I created a code snippet for you, Hope it helps!
export async function action({ request }) {
// Get data from the form.
const formData = await request.formData();
const email = formData.get("email");
const password = formData.get("password");
try {
const logInResponse = await loginUser({ email, password }); // Your API.
return logInResponse; // send a response.
} catch (error) {
return {
error: error.message,
};
}
}
export default function Login() {
const location = useLocation(); // Catch ref page.
const navigate = useNavigate(); // Redirect to page.
const actionData = useActionData(); // Catch action function.
const userFrom = location.state?.from || "/";
React.useEffect(() => {
if (actionData?.accessToken) {
navigate(userFrom, {
replace: true,
});
}
}, [actionData]); // If the action function works.
return (<h1>LoginPage</h1>);
}
If you're curious about how it works, you can take a look at this repository.