- Create Redux folder
Create store.js file
import { configureStore } from ‘@reduxjs/toolkit’
/* ——- Auth ——- */
import AuthSlice from ‘./Slices/AuthSlice’
const store = configureStore({
reducer: {
auth: AuthSlice,
},
})
export default store
Create Slice folder
Create Slice File
import { createAsyncThunk, createSlice } from ‘@reduxjs/toolkit’;
import axios from “axios”;
const initialState = {
user: “”,
success: null,
loading: false,
error: null,
};
// Login
export const register = createAsyncThunk(
“auth/register”,
async (formData, { rejectWithValue }) => { // Fix here
try {
const response = await axios.post(${process.env.REACT_APP_AUTH_URL}/register
, formData); // Fix here
const { user, token } = response.data;
console.log(user, ‘this is auth user’);
localStorage.setItem(“access_token”, JSON.stringify(token));
localStorage.setItem(“user”, JSON.stringify({
…user
}));
return { user, token };
} catch (error) {
return rejectWithValue(error.response.data);
}
}
);
————- Slice —————
// Slice
const blogSlice = createSlice({
name: ‘blog’,
initialState,
reducers: {
setBlogData: (state, action) => {
state.data = action.payload;
},
},
extraReducers: (builder) => {
builder
//Get All User
.addCase(getAllBlog.pending, (state) => {
state.loading = true;
state.error = null;
})
.addCase(getAllBlog.fulfilled, (state, action) => {
state.loading = false;
state.error = null;
state.blog = action.payload;
// Handle any state updates needed after successful API call
})
.addCase(getAllBlog.rejected, (state, action) => {
state.loading = false;
state.error = action.payload ? action.payload.message : 'Failed to post blog data';
})
//Get All User
.addCase(getBlog.pending, (state) => {
state.loading = true;
state.error = null;
})
.addCase(getBlog.fulfilled, (state, action) => {
state.loading = false;
state.error = null;
state.blog = action.payload;
// Handle any state updates needed after successful API call
})
.addCase(getBlog.rejected, (state, action) => {
state.loading = false;
state.error = action.payload ? action.payload.message : 'Failed to post blog data';
})
// Create User
.addCase(createBlog.pending, (state) => {
state.loading = true;
state.error = null;
})
.addCase(createBlog.fulfilled, (state, action) => {
state.loading = false;
state.error = null;
// Handle any state updates needed after successful API call
})
.addCase(createBlog.rejected, (state, action) => {
state.loading = false;
state.error = action.payload ? action.payload.message : 'Failed to post blog data';
})
},
});
export const { setBlogData } = blogSlice.actions;
export default blogSlice.reducer;
Kevin Neel is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.