2025-05-23 09:22:51 +08:00
|
|
|
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit';
|
|
|
|
import api from '@/services/api';
|
|
|
|
|
|
|
|
export const loginThunk = createAsyncThunk('auth/login', async (credentials, { rejectWithValue }) => {
|
|
|
|
try {
|
|
|
|
const response = await api.post('/user/login/', credentials);
|
|
|
|
if (response.code === 200) {
|
|
|
|
sessionStorage.setItem('token', response.data.token);
|
|
|
|
return response.data;
|
|
|
|
} else {
|
|
|
|
return rejectWithValue(response.message);
|
|
|
|
}
|
|
|
|
} catch (error) {
|
|
|
|
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;
|