Mental model for context based toasts #1840
-
I've just started porting my website over to Remix and I've been really impressed with what I've seen so far. The amount of state management/effect code I've been able to strip out is incredible! One stumbling block that I've run into is how toast messages should work in the new Remix world. Previously I would have used a context and handled mutations manually, something like this... const { showAlert } = useSnackbar();
const handleClick = () => {
fetch('/do-a-thing', { method: 'POST'})
.then((response) => response.json())
.then((data) => {
showAlert('All good!', 'success');
})
.catch((error) => {
showAlert('Sad times :(', 'error');
});
} Now that the mutation happens via an action i.e. no explicit event, I don't have a mental model of how I can fire toast messages. I've tried the code below but I can't get it to work... const actionData = useActionData<ActionData>();
const { showAlert } = useSnackbar();
const transition = useTransition();
// if the formError is populated, the toast shows incorrectly
// when you redirect away from current route
React.useEffect(() => {
if (actionData?.formError !== undefined && transition.submission) {
showAlert(actionData.formError, 'error');
}
}, [actionData?.formError, transition.submission, showAlert]); What am I missing? I've put together a simple repo that shows the inner workings of the context etc. in case anyone wants to spin it up. Any help would be greatly appreciated. Thanks, |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 5 replies
-
Whenever you submit a form, remix will refetch all loaders to revalidate the data. This keeps all the UI data in your nested components fresh. The flow is:
In your case, you will set error/success in the action and want to know this in a loader. You can use sessions for this. Store the information in a sessionCookie and read it in a loader / route to render your toast. |
Beta Was this translation helpful? Give feedback.
-
Beta Was this translation helpful? Give feedback.
Whenever you submit a form, remix will refetch all loaders to revalidate the data. This keeps all the UI data in your nested components fresh. The flow is:
In your case, you will set error/success in the action and want to know this in a loader. You can use sessions for this. Store the information in a sessionCookie and read it in a loader / route to render your toast.