| import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'; |
| import accountService from '../../services/accountService'; |
|
|
| |
| const initialState = { |
| items: [], |
| loading: false, |
| error: null |
| }; |
|
|
| |
| export const fetchAccounts = createAsyncThunk( |
| 'accounts/fetchAccounts', |
| async (_, { rejectWithValue }) => { |
| try { |
| const response = await accountService.getAll(); |
| return response.data.accounts; |
| } catch (error) { |
| return rejectWithValue(error.response.data); |
| } |
| } |
| ); |
|
|
| export const addAccount = createAsyncThunk( |
| 'accounts/addAccount', |
| async (accountData, { rejectWithValue }) => { |
| try { |
| const response = await accountService.create(accountData); |
| return response.data; |
| } catch (error) { |
| return rejectWithValue(error.response.data); |
| } |
| } |
| ); |
|
|
| export const deleteAccount = createAsyncThunk( |
| 'accounts/deleteAccount', |
| async (accountId, { rejectWithValue }) => { |
| try { |
| const response = await accountService.delete(accountId); |
| return { ...response.data, accountId }; |
| } catch (error) { |
| return rejectWithValue(error.response.data); |
| } |
| } |
| ); |
|
|
| |
| const accountsSlice = createSlice({ |
| name: 'accounts', |
| initialState, |
| reducers: { |
| clearError: (state) => { |
| state.error = null; |
| } |
| }, |
| extraReducers: (builder) => { |
| |
| builder |
| .addCase(fetchAccounts.pending, (state) => { |
| state.loading = true; |
| state.error = null; |
| }) |
| .addCase(fetchAccounts.fulfilled, (state, action) => { |
| state.loading = false; |
| state.items = action.payload; |
| }) |
| .addCase(fetchAccounts.rejected, (state, action) => { |
| state.loading = false; |
| state.error = action.payload?.message || 'Failed to fetch accounts'; |
| }) |
| |
| .addCase(addAccount.pending, (state) => { |
| state.loading = true; |
| state.error = null; |
| }) |
| .addCase(addAccount.fulfilled, (state, action) => { |
| state.loading = false; |
| |
| state.items = [...state.items, action.payload]; |
| }) |
| .addCase(addAccount.rejected, (state, action) => { |
| state.loading = false; |
| state.error = action.payload?.message || 'Failed to add account'; |
| }) |
| |
| .addCase(deleteAccount.pending, (state) => { |
| state.loading = true; |
| state.error = null; |
| }) |
| .addCase(deleteAccount.fulfilled, (state, action) => { |
| state.loading = false; |
| |
| state.items = state.items.filter(account => account.id !== action.payload.accountId); |
| }) |
| .addCase(deleteAccount.rejected, (state, action) => { |
| state.loading = false; |
| state.error = action.payload?.message || 'Failed to delete account'; |
| }); |
| } |
| }); |
|
|
| export const { clearError } = accountsSlice.actions; |
| export default accountsSlice.reducer; |