I have to dispatch the action that makes the request to the API to create a user. The problem is that I can’t put an awiat to the dispatch because it has no effect. I am using redux toolkit for the state. What I want to achieve is that the navigate is executed only if the dispatch is carried out successfully. I leave you my code
const onSubmit = async (data) =>{
const userInfo = {
username:data?.username,
email:data?.email,
phone:data?.phoneNumber,
password:data?.password,
}
try {
dispatch(signUp(userInfo))
navigate("/signin"); // deberia ejecutarse solo si el dispatch es exitoso
} catch (error) {
console.log(error);
}
}
async thunk
import { createAsyncThunk } from "@reduxjs/toolkit";
import axios from "axios";
export const signUp = createAsyncThunk(
"type/postData",
async (data, thunkAPI) => {
try {
const response = await axios.post("http://localhost:4001/auth/register", data);
// Si deseas obtener algo de vuelta
return response.data;
} catch (error) {
if (error.response && error.response.data && error.response.data.error) {
return thunkAPI.rejectWithValue(error.response.data.error);
} else {
throw new Error('Error fetching user applications: ' + error.message);
}
}
}
);
the slice:
import { createSlice } from "@reduxjs/toolkit";
import { signUp } from "../actions/userActions";
const initialState = {
userInfo:{},
loading: false,
error: null,
}
export const userSlice = createSlice({
name: 'user', // Corregí el nombre del slice
initialState,
reducers: {
// Aquí puedes agregar tus propias acciones si es necesario
},
extraReducers: (builder) => {
builder
.addCase(signUp.pending, (state) => {
state.loading = true;
state.error = null;
})
.addCase(signUp.fulfilled, (state) => {
state.loading = false;
state.error = null;
})
.addCase(signUp.rejected, (state, action) => {
console.log(action);
state.loading = false;
state.error = action.payload;
});
},
});
export default userSlice.reducer;
I tried to use the await before the dispatch and it has no effect, also execute the navigate() with a .then after the dispatch and I have no results either