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); } }); 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;