React/Redux not updating the state

Viewed 252

I'm just starting in redux and I want to include it on my existing app. What I want to do is to store my login response for me to use the user details on other page.

LandingPage.js

import { useDispatch } from 'react-redux'

function LandingPage(){
  const dispatch = useDispatch();
  const authLogin = async()=>{
  const response = await axios.get('/api',)
  let responseValue = response.data.success
  if(responseValue === true) {
     const parsedData = JSON.parse(response.data.resp)
     dispatch({
       type: 'SAVE_AUTH',
       payload: {
         isLoggedIn: responseValue,
         username: parsedData.data.user.userName,
         token: parsedData.data.token
       }
     })
  }
useEffect(() => {
authLogin();
  }, [])
return (
<div>
  <label>Authenticating....</label>
  <Login1 /> //updated based on @LindaPaiste's answer
</div>
export default LandingPage;

MainLanding.js

import React from 'react'
import Login1 from './Login1'
function MainLanding(){
return(
    <div>
        <h1>User Login Details</h1>
        <Login1 /> //Nothing hapens here
    </div>
)
}
export default MainLanding;

Login1.js

import React from 'react'
import LoginDetailsx from './LoginDetailsx'
import { useSelector } from 'react-redux'
function Login1(){
const userLoginDetails = useSelector((state) => state.loginDetails)
console.log('userLoginDetails',userLoginDetails)
return(
    <div>
        <h2>Login Details</h2>
        <LoginDetailsx isLogin={userLoginDetails.isLoggedIn} username={userLoginDetails.username} token={userLoginDetails.token}/>
        })}
        
    </div>
)}
export default Login1;

loginDetailsReducer.js

const initialState = [
{
    isLoggedIn: false,
    
}];

const loginDetailsReducer = (state = initialState, action) => {
const { type, payload } = action;
console.log('typex',type)
console.log('payloadx',payload)

switch(type){
    case "SAVE_AUTH":
        alert('dasdasd')
        return payload;
    case "LOGOUT_AUTH":
        return initialState
    default:
        return state;
}
}
export default loginDetailsReducer;

rootReducer.js

import { combineReducers } from 'redux'
import loginDetailsReducer from '../reduxReducers/loginDetailsReducer'
const rootReducer = combineReducers({
  loginDetails: loginDetailsReducer
});
export default rootReducer;

store.js

import { createStore } from 'redux'
import rootReducer from '../reduxReducers/rootReducer'
const store = createStore(rootReducer);
export default store;

LoginDetailsx.js

import React from 'react'
function LoginDetailsx(props){
return(
    <div>
        <p>Details: isloggedin: {props.isloggedin}, username: {props.username}, token: {props.token}</p>
    </div>
   )
}
export default LoginDetailsx;

This is what I'm getting on MainLanding.js after successful login. enter image description here

and this is what i'm getting on LandingPage.js console.log enter image description here

1 Answers

State Shape

While not necessarily a problem, it really doesn't make sense that the loginDetails state should be an array. Only one user should be logged in at a time, so it should just be an object with the user details. That makes your reducer extremely simple (as always Redux Toolkit can make it even simpler).

You'll want to add a logout case too. isLoggedIn should be a boolean instead of a string. I personally think that undefined makes more sense than '' for username and token when there is no logged in user but that's up to you.

const initialState = {
    isLoggedIn: false,
    // no username or token when logged out
};

const loginDetailsReducer = (state = initialState, action) => {
    const { type, payload } = action;
    switch(type) {
        case "SAVE_AUTH":
            // replace the state with the action payload
            return payload;
        case "LOGOUT_AUTH":
            // revert to initial state
            return initialState;
        default:
            return state;
    }
}

export default loginDetailsReducer;

Logging In

I was going to say that asynchronous actions like API calls need to be done inside a useEffect hook in the component. You can use an empty dependency array to run the effect once when the component is mounted.

useEffect(() => {
    authLogin();
}, []);

But now I'm looking at your image and it seems like you are executing the action in response to a button click, so that's fine too.

axios handles JSON parsing so you should not need to use JSON.parse() (unless your API is returning strange data).

function MainLanding() {
  const isLoggedIn = useSelector((state) => state.loginDetails.isLoggedIn);

  // access dispatch function
  const dispatch = useDispatch();

  // define the function to log in
  const authLogin = async () => {
    const response = await axios.get("/api");
    const data = response.data;
    if (data.success === true) {
      dispatch({
        type: "SAVE_AUTH",
        payload: {
          isLoggedIn: true,
          username: data.resp.user.userName,
          token: data.resp.data.token
        }
      });
    }
  };

  return (
    <div>
      {isLoggedIn ? (
        <>
          <h1>User Login Details</h1>
          <Login1 />
        </>
      ) : (
        <button onClick={authLogin}>Log In</button>
      )}
    </div>
  );
}
Related