Redux with react, how to pass and receive the data

124 Views Asked by At

I am doing a login form for react and I am using redux for the state management. This will be connected to server but I want to try it first with a some data.

I don't know how to pass data coming from the user input to the reducers. Here is my code for the onsubmit hadler:

const [isAuthenticated, setIsAuthenticated] = useState(false);
const [token, setToken] = useState(null);

const LoginHandler = (e) => {
        e.preventDefault();
    
        const userCreds = {
          email: email,
          password: password,
        };
    
        setToken(Math.random().toString());
    
        dispatch(login());
      };

and here is my code for the slice:

export const authSlice = createSlice({
  name: "auth",
  initialState,
  reducers: {
    login: (state) => {
      state.authenticated = "";
      state.token = "";
      state.currentUser = {
        email: "",
        password: "",
      };
    },

    logout: (state) => {
      state.authenticated = false;
      state.token = null;
      state.currentUser = null;
    },
  },
});

Please teach me how to pass the data from that function to my SLice. Thank you so much.

1

There are 1 best solutions below

0
Harrison On

Looks like you're close, if you're following this example you just need to make sure your exports are in order.
Then adjust your functions to more closely match the example linked above.

Your login function should look like this:

    login: (state, action) => {
      // I'm ignoring these two for now
      // state.authenticated = "";
      // state.token = "";
      state.currentUser = {
        email: action.payload.email,
        password: action.payload.password,
      };
    },

and your login function like this:

const LoginHandler = (e) => {
        e.preventDefault();
    
        const userCreds = {
          email: email,
          password: password,
        };
    
        setToken(Math.random().toString());
    
        dispatch(login(userCreds));
      };

You need to pass in the action payload when you dispatch the action.