-
-
Save codecademydev/cbcfbfae923391902499ed6b75d418ca to your computer and use it in GitHub Desktop.
Codecademy export
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
import { createAsyncThunk, createSlice } from "@reduxjs/toolkit"; | |
import { | |
addFavoriteRecipe, | |
removeFavoriteRecipe, | |
} from "../favoriteRecipes/favoriteRecipesSlice"; | |
import { selectSearchTerm } from "../search/searchSlice"; | |
// createAsyncThunk simplifies our Redux app by returning an action creator that dispatches promise lifecycle actions for us so we don't have to dispatch them ourselves. | |
export const loadRecipes = createAsyncThunk( | |
"allRecipes/getAllRecipes", | |
async () => { | |
const data = await fetch("api/recipes?limit=10"); | |
const json = await data.json(); | |
return json; | |
} | |
); | |
const sliceOptions = { | |
name: "allRecipes", | |
initialState: { | |
recipes: [], | |
isLoading: false, | |
hasError: false | |
}, | |
reducers: {}, | |
extraReducers: { | |
[loadRecipes.pending]: (state, action) => { | |
state.isLoading = true; | |
state.hasError = false; | |
}, | |
[loadRecipes.fulfilled]: (state, action) => { | |
state.recipes = action.payload; | |
state.isLoading = false; | |
state.hasError = false; | |
}, | |
[loadRecipes.rejected]: (state, action) => { | |
state.isLoading = false; | |
state.hasError = true; | |
} | |
} | |
} | |
export const allRecipesSlice = createSlice(sliceOptions); | |
export const selectAllRecipes = (state) => state.allRecipes.recipes; | |
export const selectFilteredAllRecipes = (state) => { | |
const allRecipes = selectAllRecipes(state); | |
const searchTerm = selectSearchTerm(state); | |
return allRecipes.filter((recipe) => | |
recipe.name.toLowerCase().includes(searchTerm.toLowerCase()) | |
); | |
}; | |
export default allRecipesSlice.reducer; |
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
// Without createAsyncThunk, we have to dispatch pending/fulfilled/rejected actions ourself. | |
export const loadRecipes = () => { | |
return async (dispatch, getState) => { | |
dispatch({type: "allRecipes/getAllRecipes/pending"}) | |
try { | |
const data = await fetch("api/recipes?limit=10"); | |
const json = await data.json(); | |
dispatch({type: "allRecipes/getAllRecipes/fulfilled", payload: json}) | |
} catch (err) { | |
dispatch({type: "allRecipes/getAllRecipes/rejected", payload: err}) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment