CreatorCenter_OOIN/src/store/slices/authSlice.js
2025-05-29 17:13:27 -04:00

57 lines
1.7 KiB
JavaScript

import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import api from '@/services/api';
import { setNotificationBarMessage } from './notificationBarSlice';
export const loginThunk = createAsyncThunk('auth/login', async (credentials, { rejectWithValue, dispatch }) => {
try {
const response = await api.post('/user/login/', credentials);
if (response.code === 200) {
sessionStorage.setItem('token', response.data.token);
return response.data;
} else {
throw new Error(response.message);
}
} catch (error) {
dispatch(setNotificationBarMessage({ message: error.message, type: 'error' }));
return rejectWithValue(error.message);
}
});
const initialState = {
user: null,
isAuthenticated: false,
isLoading: false,
};
const authSlice = createSlice({
name: 'auth',
initialState,
reducers: {
setUser: (state, action) => {
state.user = action.payload;
},
clearUser: (state) => {
state.user = null;
state.isAuthenticated = false;
},
},
extraReducers: (builder) => {
builder.addCase(loginThunk.pending, (state, action) => {
state.isLoading = true;
});
builder.addCase(loginThunk.fulfilled, (state, action) => {
state.user = action.payload;
state.isAuthenticated = true;
state.isLoading = false;
});
builder.addCase(loginThunk.rejected, (state, action) => {
state.isAuthenticated = false;
state.isLoading = false;
});
},
});
export const { setUser, clearUser } = authSlice.actions;
export default authSlice.reducer;