Search code examples
typescriptauthenticationreduxdispatchthunk

How to retrieve data after successful redux dispatch inside a SignIn form component


I have a SignIn form. When the login and pass submitted I am using dispatch to send data and get the JWT token.

Form code:

import React from 'react';
import Avatar from '@mui/material/Avatar';
import Button from '@mui/material/Button';
import TextField from '@mui/material/TextField';
import FormControlLabel from '@mui/material/FormControlLabel';
import Checkbox from '@mui/material/Checkbox';
import Link from '@mui/material/Link';
import Paper from '@mui/material/Paper';
import Box from '@mui/material/Box';
import Grid from '@mui/material/Grid';
import LockOutlinedIcon from '@mui/icons-material/LockOutlined';
import Typography from '@mui/material/Typography';
import { signIn } from './../../Services/Effects/effects'
import { useAppDispatch} from '../../Services/hooks';
import { useNavigate } from 'react-router-dom';

function SignIn() {

  const dispatch = useAppDispatch();

  const navigate = useNavigate();

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

    const data = new FormData(event.currentTarget);

    try {

      const userToken = dispatch(signIn(data.get('email') as string, data.get('password') as string));

      console.log(userToken);

    } catch (error) {
      console.log(error);
    }
  };

  return (
//  UI code

}

signIn code to call API service:

import { AppThunk } from '../store';
import { SignInParams } from './../Types/auth.types';
import { signInRequest, signInSuccess, signInError } from './../Actions/auth.actions';
import * as authService from './../auth.service';

export const signIn = (email: SignInParams['email'], password: SignInParams['password']): AppThunk => async (dispatch , getState ) => {
  dispatch(signInRequest());
  try {
    const userToken = await authService.signIn(email, password);
    return dispatch(signInSuccess(userToken));
  } catch {
    return dispatch(signInError());
  }
};

Interfaces:

export interface UserToken {
    token: string;
}

export interface SignInSuccess extends Action {
    type: 'signInSuccess';
    userToken: UserToken;
}

On successfull sign in console.log(userToken) is following:

Promise {<pending>}
[[Prototype]]
: 
Promise
[[PromiseState]]
: 
"fulfilled"
[[PromiseResult]]
: 
Object
type
: 
"signInSuccess"
userToken
: 
{token: 'eyJhbGciOiJSU .....'}
[[Prototype]]
: 
Object

What is the right method to check the promise result and if signInSuccess use navigate to dashboard ?


Solution

  • I've found a solution using store.subscribe.

    store.subscribe(() => {
        const state = store.getState();
        // do whatever you want with the new state
        console.log(state.userToken.token);  
    });