Skip to content
Advertisement

How to pass the object to action in slice?

I need to pass userId and userNickname to action authUser in authSlice reducer.

authSlice:

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

const initialState = {
    userId : null,
    userNickame : "",
    isAuth : false,
    isAdmin : false, 
}

export const authSlice = createSlice({
    name : 'auth',
    initialState,
    reducers : {
        authUser : (state, action) => {
            //const {userId, userNickame} = action.payload;
            state.userId = userId;
            state.userNickame = userNickame;
            state.isAuth = true;
        },
    },
})

export const { authUser } = authSlice.actions
export default authSlice.reducer

calling dispatcher

//...

const dispatch = useDispatch();
const userId = useSelector((state) => state.userId);
const userNickname = useSelector((state) => state.userNickname);

//...

dispatch(authUser(/* I need to pass userId and userNickname here */));

Advertisement

Answer

Simply

dispatch(authUser({ userId, userNickname }));

which is equivalent to

dispatch(authUser({ userId: userId, userNickname: userNickname }));

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement