Chirag Maurya
Chirag Maurya

Reputation: 73

Reactjs - My redux is not storing the user

I am trying to store a user using redux. I want to then use the user's details to help filter data and also display on the navbar to show if logged in. I am able to maintain the user to stay loggen in by using sessions and cookies, no hitches there.

In redux, my store is being created succesfully and the user is properly being initialized to null before updating. However, on logging in, the user is not being updated in the redux store. Even after logging in the user stays null yet in my session, the user is logged in.

index.js:

import React from "react";
import ReactDOM from "react-dom";
import "./index.css";
import App from "./App";
import reportWebVitals from "./reportWebVitals";
import "bootstrap/dist/css/bootstrap.min.css";

import { Provider } from "react-redux";
import store from "./app/store";

ReactDOM.render(
  <React.StrictMode>
    <Provider store={store}>
      <App />
    </Provider>
  </React.StrictMode>,
  document.getElementById("root")
);
reportWebVitals();

login_componenet.js:

//import "bootstrap/dist/css/bootstrap.min.css";
import React, { useState, useEffect } from "react";
import axios from "axios";
import { useDispatch } from "react-redux";

function Login() {
  const [LoginID, setLoginID] = useState("");
  const [Password, setPassword] = useState("");
  const [LoginStatus, setLoginStatus] = useState("");
  const [email, setEmail] = useState("");
  const [logID, setLogID] = useState("");
  const [id, setId] = useState("");

  axios.defaults.withCredentials = true;

  const login = (event) => {
    axios
      .post("http://localhost:8000/login", {
        LoginID: LoginID,
        Password: Password,
      })
      .then((response) => {
        console.log(response.data.result[0]);
        if (response.data.message) {
          setLoginStatus(response.data.message);
        } else {
          setLoginStatus(response.data[0].UserFullName);
          setEmail(response.data.result[0].UserEmailID);
          setLogID(response.data.result[0].LoginID);
          setId(response.data.result[0].UserID);
        }
      });
  };

  const dispatch = useDispatch();

  const handleSubmit = (e) => {
    e.preventDefault();
    dispatch(
      login({
        name: LoginStatus,
        LoginId: logID,
        email: email,
        id: id,
        loggedIn: true,
      })
    );
  };

  useEffect(() => {
    axios.get("http://localhost:8000/login").then((response) => {
      if (response.data.loggedIn === true) {
        setLoginStatus(response.data.user[0].UserFullName);
      }
    });
  }, []);

  return (
    <div className="App">
      <div className="auth-wrapper">
        <div className="auth-inner">
          <form onSubmit={(e) => handleSubmit(e)}>
            <h3>Log In</h3>

            <div className="form-group ">
              <label>Login ID</label>
              <input
                type="text"
                className="form-control"
                placeholder="Login ID"
                onChange={(e) => {
                  setLoginID(e.target.value);
                }}
              />
            </div>

            <div className="form-group">
              <label>Password</label>
              <input
                type="password"
                className="form-control"
                placeholder="Password"
                onChange={(e) => {
                  setPassword(e.target.value);
                }}
              />
            </div>

            <button className="btn btn-primary btn-block" onClick={login}>
              Login
            </button>
          </form>
          <h1>{LoginStatus}</h1>
        </div>
      </div>
    </div>
  );
}

export default Login;

store.js:

import { configureStore } from "@reduxjs/toolkit";
import userReducer from "../features/userSlice";

export default configureStore({
  reducer: {
    user: userReducer,
  },
});

userSlice.js

import { createSlice } from "@reduxjs/toolkit";

export const userSlice = createSlice({
  name: "user",
  initialState: {
    user: null,
  },
  reducers: {
    login: (state, action) => {
      state.user = action.payload;
    },
    logout: (state) => {
      state.user = null;
    },
  },
});

export const { login, logout } = userSlice.actions;
export const selectUser = (state) => state.user.user;
export default userSlice.reducer;

Upvotes: 0

Views: 99

Answers (1)

SOReader
SOReader

Reputation: 6017

To my taste you should be dispatching information about successful login from then body of axios call. What you are currently doing is dispatching result of login call which is undefined (nothing is being returned from login).

Here's a link to redux docs on how dispatch works: https://react-redux.js.org/api/hooks#usedispatch

EDIT

Assuming we're still on the original code, if you did something like that all should work fine:

login_component.js

// import
>>> import { login as loginAction } from '<PATH_TO_USERSLICE.JS>' <<<


// where the login function is declared
  const login = (event) => {
    axios
      .post("http://localhost:8000/login", {
        LoginID: LoginID,
        Password: Password,
      })
      .then((response) => {
        console.log(response.data.result[0]);
        if (response.data.message) {
          setLoginStatus(response.data.message);
        } else {
          setLoginStatus(response.data[0].UserFullName);
          setEmail(response.data.result[0].UserEmailID);
          setLogID(response.data.result[0].LoginID);
          setId(response.data.result[0].UserID);
>>>          dispatch(loginAction(response.data.user[0])); <<<
        }
      });
  };  

DISCLAIMER Haven't actually run that but this should work.

Upvotes: 1

Related Questions