I have a page where I can see the detail of a recipe. Im grabbing all the data for the recipe from my store for example store.recipes.recipeDetail
. In my RecipeDetail
component, I use useEffect
to fetch the data on component load by dispatching an action.
export default function RecipeDetail() {
// Hooks
const params = useParams()
const dispatch = useDispatch()
// Get redux state
const recipeDetail = useSelector((store) => store.recipes.recipeDetail)
// Reset store and fetch data on page load
useEffect(()=>{
dispatch(recipesActions.fetchRecipeAction(params.slug))
}, [dispatch, params])
My redux looks something like this (I'm using Redux Toolkit)
import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import * as API from 'services/api'
// Async actions
const fetchRecipeAction = createAsyncThunk(
'recipes/fetchRecipe',
async (slug, thunkAPI) => {
const response = await API.fetchRecipe(slug)
return response.data
}
)
const initialState = {
recipeDetail: null
}
const coreSlice = createSlice({
name: 'recipes',
initialState: initialState,
reducers: {
},
extraReducers: {
[fetchRecipeAction.fulfilled]: (state, action) => {
state.recipeDetail = action.payload
}
}
}
)
// Exports actions, asyncActions and reducer
export { fetchRecipeAction }
export default coreSlice.reducer
Now inside that Recipe Detail page, I have a link to "other recipes you might like", when I click on a recipe, a new recipe opens but the old recipe is still visible until the request to the backend is done.
I thought I could create a new action to reset the info inside de redux store:
reducers: {
resetRecipeDetail: (state, action) => {
state.recipeDetail = initialState.recipeDetail
}
}
And then inside my component, I dispatch this action on component unload:
// Reset recipeDetail store on component unload
useEffect(()=>()=>{
dispatch(stratsActions.resetStratDetail())
}, [dispatch])
But this action doesn't get dispatched when switching from one recipe to another one, so the store is not reset. (im guessing because the route doesnt change, only the recipe slug)
Is this the correct method? If so how can I make it work so it resets the store correctly? Is there a better method?
Many thanks
UPDATE: I've been able to dispatch the "resetRecipeDetail" action from within the fetchRecipeAction async action so anytime I fetch a new recipe the store will be cleared automatically. Not sure if this is the best method. What do you think?
const fetchRecipeAction = createAsyncThunk(
'recipes/fetchRecipe',
async (slug, thunkAPI) => {
thunkAPI.dispatch(coreSlice.actions.resetRecipeDetail()) <-----ADDED THIS
const response = await API.fetchRecipe(slug)
return response.data
}
)