#useActionData for different routes

1 messages · Page 1 of 1 (latest)

echo sapphire
#

I have a main page that has multiple <Form>s that GET and POST to different routes, e.g. a home page with a search input that GETs from /search.tsx and POSTs to /saveSearch.tsx

I want to be able to handle errors, but useActionData only displays information for the current route's action. How can I get error information in this case? Do I have to use useFetcher?

proper falcon
#

before you submit your data on the other page, you can add additional form data

const handleSubmit(event: React.FormEvent<HTMLFormElement>){

const formData = new FormData(event.currentTarget); // get all existing form data from the submit event
formData.append("location", "this pages url location");
submit(formData, { action="/where/to/submit" });
}

Now that you have this location value present in your action function.
You can Flash errors using a session cookie. https://remix.run/docs/en/v1/api/remix#createcookiesessionstorage

To handle the errors you can

sessionIdSession.flash("someErrorName", "We've sent you an error.");
            throw redirect("/somelocation", {
                headers: {
                    "Set-Cookie": await sessionStorage.commitSession(sessionIdSession),
                },
            });

Now in your loader you can read the session data, and get your errors on any page, even though you submit to a different route

#

to resolve errors I made a helper function that gets my cookie, and returns any errors from common error names I use

echo sapphire
#

that seems way more complicated than useFetcher and equally lacks non-js support 😦