Redux State updates when a form is submitted

Advertisements

I am developing a react application and using redux toolkit for state management. I have a user logged in with JWT store in the local storage and the details of the user are stored in state.auth. This user can create other users using a form. After filling the form details, when the form is submitted, userRegister() action from the authSlice is dispatched.

This is the handleSubmit function from where the registerUser action is called:

    const handleSubmit = (event) => {
        event.preventDefault();

        const userData = {
            name,
            email,
            password,
            confirmPassword,
            userType,
            userDevices
        }
        dispatch(registerUser(userData))
    };

This is the authSlice.js containing the registerUser function

const initialState = {
    userData: {}, //for user data
    userToken: null, // for JWT
    isAuthenticated: false, 
    error: null,

}

export const authSlice = createSlice({
    name: 'auth',
    initialState,
    reducers: {
        //Setting user in redux store
        setUser:(state, action) => {
            state.loading = false
            state.isAuthenticated = true
            state.userData = action.payload.user
            state.userToken = action.payload.token 
        },

        // Register user
        registerUser: async (state, action) => {
            try{
                const userData = action.payload
                console.log("User Dataaaaa from action: ", userData);
                
                const config = {
                    headers: {
                        'Content-Type':'application/json'
                    }
                }
                const data = await axios.post(`${backendURL}/api/user`,
                    userData,
                    config
                )
                console.log("Data: ", data);
                console.log("State: ", state);
            }
            catch(err){
                console.log(err);
            }
        },
.
.
.
.

The problem is when registerUser function is executed. The redux state gets updated and the the user state becomes empty, navigating the app to the login page again. However, I am not updating the state in the registerUser function.

Also when the login page is reloaded, the user state is again filled with userData as the JWT token is still stored in the local storage because logout was not called from anywhere.

This is the image from the redux dev tool when the registerUser action is called

I am facing this weird issue and unable to resolve it. Any help would be great. Thank you.

I have tried return the {…state} from the registerUser function, but still the issue persists.

>Solution :

You are not allowed to execute side effect like API requests in reducers – reducers have to be synchronous, pure and side-effect-free. The reducer you have written here accidentally replaces your whole slice with a Promise.

What you are a looking to do here needs some kind of middleware. If API interactions don’t happen a lot in your application, you should look into createAsyncThunk. If it’s a more common thing, look into RTK Query.

Both of these are handled in the official Redux tutorial which I would highly recommend to you.

Leave a ReplyCancel reply