How do I dispatch a redux action within the action function of a React component?

16 Views Asked by At

I'm building an app using React, React-Router and Redux. Reading about React-Router, I'm trying to follow what I believe is the most current way of doing things and use 'action' and 'loader' functions on some of my Routes.

One of my components is a Login form and I'm trying to use React-Router to manage the form data and submission events. As such, I have an 'action' prop on the route, as shown below:

<Route path='/login' element={<Login />} loader={loginLoader} action={loginAction} />

The loginLoader and loginAction functions are stored in the Login.tsx file as named exports.

The action function is as below:

export const action = async ({ request }: { request: Request }) => {

  const formData = await request.formData();
  const email = formData.get("email");
  const password = formData.get("password");
  const pathname = new URL(request.url).searchParams.get("redirectTo") || "/dashboard";
  const dispatch = useDispatch(); 

  try {
    await onLogin({ email, password });
    dispatch(authenticateUser());
    localStorage.setItem("isAuth", "true");
    return redirect(pathname);
  } catch (error: any) {
    console.log(error);

    return "Couldn't log user in";
  }

The action function is imported into my App.tsx file and then passed to the 'action' prop on the route containing the component.

Essentially, my problem is that I can't use hooks within the action function and therefore can't dispatch a redux update, it needs to be within the component itself. However, if it's in the component, then it's not going to enact when the action function runs. This means I have to go back to the old way of managing my form completion and submission, using state and a submission function and then update Redux within the component itself.

I'm sure I'm missing something here, so wondered if anyone can offer any advice? I'm happy to provide any more required info.

Thank you!

0

There are 0 best solutions below