CreatorCenter_OOIN/src/store/slices/authSlice.js

57 lines
1.7 KiB
JavaScript
Raw Normal View History

2025-05-23 09:22:51 +08:00
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
import api from '@/services/api';
2025-05-30 05:13:27 +08:00
import { setNotificationBarMessage } from './notificationBarSlice';
2025-05-23 09:22:51 +08:00
2025-05-30 05:13:27 +08:00
export const loginThunk = createAsyncThunk('auth/login', async (credentials, { rejectWithValue, dispatch }) => {
2025-05-23 09:22:51 +08:00
try {
const response = await api.post('/user/login/', credentials);
if (response.code === 200) {
sessionStorage.setItem('token', response.data.token);
return response.data;
} else {
2025-05-30 05:13:27 +08:00
throw new Error(response.message);
2025-05-23 09:22:51 +08:00
}
} catch (error) {
2025-05-30 05:13:27 +08:00
dispatch(setNotificationBarMessage({ message: error.message, type: 'error' }));
2025-05-23 09:22:51 +08:00
return rejectWithValue(error.message);
}
});
2025-05-15 10:42:39 +08:00
const initialState = {
user: null,
isAuthenticated: false,
2025-05-23 09:22:51 +08:00
isLoading: false,
2025-05-15 10:42:39 +08:00
};
const authSlice = createSlice({
name: 'auth',
initialState,
reducers: {
setUser: (state, action) => {
state.user = action.payload;
},
2025-05-23 09:22:51 +08:00
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;
});
2025-05-15 10:42:39 +08:00
},
});
2025-05-23 09:22:51 +08:00
export const { setUser, clearUser } = authSlice.actions;
2025-05-15 10:42:39 +08:00
export default authSlice.reducer;