Home > Back-end >  How to display response from an api call to a component whilst using redux?
How to display response from an api call to a component whilst using redux?

Time:09-22

I am trying to implement an authentication system into my project and have been following this tutorial https://youtu.be/LKlO8vLvUao . The system works however I am trying to display the error message on a failed login attempt and I cannot figure out how to get the error message from the reducer to the component where I'd like to display it (preferably using a [msg,setMsg] hook)

Here is my code from the action where I capture the error response and pass it to reducer:

export const signin = (formData, history) => async (dispatch) => {
try {
    const { data }  = await API.signIn(formData);
    dispatch({ type: AUTH, data });

    history.push('/')
}
catch (error){
    const data = error.response.data;
    dispatch({ type: "AUTH_FAIL", data })

 }
}

Here is my reducer:

import { AUTH, LOGOUT } from '../constants/actionTypes'

const authReducer = (state = { authData: null }, action) => {
   switch (action.type){
      case AUTH:
        localStorage.setItem('profile', JSON.stringify({ ...action?.data }))
        return { ...state, authData: action?.data};
      case LOGOUT:
        localStorage.clear();
        return { ...state, authData: null };
    case "AUTH_FAIL":
        return { ...state, authData: action?.data};

    default:
        return state;
}
}

export default authReducer; 

CodePudding user response:

Where you are defining the state for this reducer, break it into two parts.one being authData as it is now, the second being error. When dispatching AUTH_FAIL, what you should return in the reducer, is the error instead of the authData. Now in your component you can call the state anyway you like and use the updated state. I know of 2 ways for doing this: 1-mapStatetoProps 2-store.subscribe() and store.getState()

CodePudding user response:

In Reducer create initiateState object

const initiateState: {
authData: null,
error: null
}

as you did in action

catch (error){
    **const data = data.response.error;**
    dispatch({ type: "AUTH_FAIL", data })

 }

also change reducer , and send the amount of action.data to error

const authReducer = (state = initiateState, action) => {
   ....//your code
       case "AUTH_FAIL":
        return { ...state, error: action.data};

    default:
        return state;
   }
}

using Hooks this equal to mapStateToProps

  const error= useSelector((state) => state.error)
  • Related