Files
Checkmate/Client/src/Features/Auth/authSlice.js
T

71 lines
1.9 KiB
JavaScript
Raw Normal View History

2024-06-07 16:17:10 -07:00
import axios from "axios";
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit";
import { jwtDecode } from "jwt-decode";
const BASE_URL = import.meta.env.VITE_APP_API_BASE_URL;
const initialState = {
isLoading: false,
authToken: "",
2024-06-07 16:17:10 -07:00
user: "",
success: null,
msg: null,
};
export const register = createAsyncThunk(
"auth/register",
async (form, thunkApi) => {
try {
const res = await axios.post(`${BASE_URL}/auth/register`, form);
return res.data;
} catch (error) {
return thunkApi.rejectWithValue(error.response.data);
}
}
);
2024-06-10 10:38:00 -07:00
export const login = createAsyncThunk("auth/login", async (form, thunkApi) => {
2024-06-10 11:53:10 -07:00
try {
const res = await axios.post(`${BASE_URL}/auth/login`, form);
return res.data;
} catch (error) {
return thunkApi.rejectWithValue(error.response.data);
}
2024-06-10 10:38:00 -07:00
});
2024-06-10 12:24:17 -07:00
const handleAuthFulfilled = (state, action) => {
state.isLoading = false;
state.success = action.payload.success;
state.msg = action.payload.msg;
state.authToken = action.payload.data;
2024-06-10 12:24:17 -07:00
const decodedToken = jwtDecode(action.payload.data);
const user = { ...decodedToken };
state.user = user;
};
const handleAuthRejected = (state, action) => {
state.isLoading = false;
state.success = action.payload.success;
state.msg = action.payload.msg;
};
2024-06-07 16:17:10 -07:00
const authSlice = createSlice({
name: "auth",
initialState,
reducers: {},
extraReducers: (builder) => {
builder
2024-06-10 11:53:10 -07:00
// Register thunk
2024-06-07 16:17:10 -07:00
.addCase(register.pending, (state, action) => {
state.isLoading = true;
})
2024-06-10 12:24:17 -07:00
.addCase(register.fulfilled, handleAuthFulfilled)
.addCase(register.rejected, handleAuthRejected)
2024-06-10 11:53:10 -07:00
// Login thunk
.addCase(login.pending, (state, action) => {
state.isLoading = true;
})
2024-06-10 12:24:17 -07:00
.addCase(login.fulfilled, handleAuthFulfilled)
.addCase(login.rejected, handleAuthRejected);
2024-06-07 16:17:10 -07:00
},
});
export default authSlice.reducer;