-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Add: categorySlice include it to the store and call it
- Loading branch information
1 parent
79dc518
commit 2c943f4
Showing
3 changed files
with
60 additions
and
3 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,54 @@ | ||
import { createAsyncThunk, createSlice } from '@reduxjs/toolkit' | ||
import axios from 'axios' | ||
|
||
export interface Category { | ||
id: string | ||
name: string | ||
books: string[] | ||
created_at: string | ||
updated_at: string | ||
} | ||
|
||
type initialState = { | ||
categoriesData: Category[] | ||
isLoading: 'idle' | 'loading' | 'succeeded' | 'failed' | ||
error: string | null | ||
} | ||
|
||
const initialState: initialState = { | ||
categoriesData: [], | ||
isLoading: 'idle', | ||
error: '', | ||
} | ||
|
||
export const fetchCategories = createAsyncThunk( | ||
'categories/fetchCategories', | ||
async () => { | ||
const response = await axios.get( | ||
'https://helm-bookstore-api.onrender.com/api/categories/' | ||
) | ||
return response.data | ||
} | ||
) | ||
|
||
export const categorySlice = createSlice({ | ||
name: 'categories', | ||
initialState, | ||
reducers: {}, | ||
extraReducers: (builder) => { | ||
builder | ||
.addCase(fetchCategories.pending, (state) => { | ||
state.isLoading = 'loading' | ||
}) | ||
.addCase(fetchCategories.fulfilled, (state, action) => { | ||
state.isLoading = 'succeeded' | ||
state.categoriesData = action.payload.categories | ||
}) | ||
.addCase(fetchCategories.rejected, (state, action) => { | ||
state.isLoading = 'failed' | ||
state.error = action.error.message || 'Unknown error' | ||
}) | ||
}, | ||
}) | ||
|
||
export const { actions, reducer } = categorySlice |