I am working on integrating Redux into my project, specifically focusing on user authentication. Below is the code snippet for my authUserSlice
. I am encountering an issue when trying to dispatch the signup
action in a NextJS Component. Despite handling the promise with a try-catch
block, I am facing difficulties.
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit';
import authService from './authService';
interface Form {
fullname: string;
username: string;
password: string;
dateofbirth: string;
status: string;
}
interface AuthState {
user: Form | null;
isError: boolean;
isSuccess: boolean;
isLoading: boolean;
message: string;
}
const initialState: AuthState = {
user: null,
isError: false,
isSuccess: false,
isLoading: false,
message: '',
};
// Register user
export const signup = createAsyncThunk(
'user/register',
async (user: Form, thunkAPI) => {
try {
const response = await authService.signup(user);
return response.data;
} catch (error) {
return thunkAPI.rejectWithValue(error);
}
}
);
export const authSlice = createSlice({
name: 'user',
initialState,
reducers: {
resetAuthUser: (state) => {
state.isLoading = false;
state.isSuccess = false;
state.isError = false;
state.message = '';
state.user = null;
},
},
extraReducers: (builder) => {
builder
.addCase(signup.pending, (state) => {
state.isLoading = true;
})
.addCase(signup.fulfilled, (state, action) => {
state.isLoading = false;
state.isSuccess = true;
state.user = action.payload;
})
.addCase(signup.rejected, (state, action) => {
state.isLoading = false;
state.isError = true;
state.message = action.payload as string;
state.user = null;
});
},
});
export const { resetAuthUser } = authSlice.actions;
export default authSlice.reducer;
//This is my sample sign up form, i filled out the formData with sample data.
import React, { useState } from 'react';
import type { RootState } from '@/lib/store';
import { unwrapResult } from '@reduxjs/toolkit';
import { useSelector, useDispatch } from 'react-redux';
import { signup, resetAuthUser } from '@/lib/features/authUserSlice'; // Import reset action
interface Form {
fullname: string,
username: string;
password: string;
dateofbirth: string;
status: string;
}
const SignUp = () => {
const [formData, setFormData] = useState<Form>({
fullname: 'Dummy Name',
username: 'Dummy122',
password: 'Dummy1234',
dateofbirth: '',
status: ''
});
const { username, password } = formData;
const count = useSelector((state: RootState) => state.counter.value);
const dispatch = useDispatch();
const onSubmit = async () => {
dispatch(signup(formData))
};
I tried changing the type, i thought it would resolve the problem and still getting the same error.