I'm building a CRUD application using redux toolkit and firestore, and I cannot figure out how to delete an item from firestore, and I really don't know why the following code isn't working. Here's the relevant code from the slice:
export const recipeSlice = createSlice({
name: 'recipesSlice',
initialState: {
recipes: []
},
reducers: {
ADD_RECIPE: (state, action) => {
state.recipes.push(action.payload)
},
DELETE_RECIPE: (state, action) => {
state.recipes = state.recipes.filter((recipe) => recipe.recipeId !== action.payload.recipeId)
},
extraReducers: (builder) => {
builder.addCase(getRecipes.fulfilled,(state, {payload}) => {
state.recipes = payload
})
.addCase(addRecipeFirestore.fulfilled, (state, {payload}) => {
state.recipes = payload
})
}
})
And here are the two async thunks that work:
export const getRecipes = createAsyncThunk(
'recipes/getRecipes',
async () => {
const snapshot = await getDocs(collection (db, 'recipes'))
const array = []
snapshot.forEach((doc) =>{
array.push(doc.data())
})
return array
}
)
export const addRecipeFirestore = createAsyncThunk(
'recipes/addRecipe',
async (newRecipe) => {
const docRef = await addDoc(collection(db, "recipes"), newRecipe)
console.log(docRef.data())
return docRef.data()
}
)
And here is the one that I cannot, for the life of me make work:
export const deleteRecipe = ({recipeId}) => {
return async (dispatch) => {
const docRef = doc(db, "recipes", `${recipeId}`)
await deleteDoc(docRef)
dispatch(DELETE_RECIPE({recipeId}))
}
}
I didn't use createAsyncThunk because it didn't seem to be a good use case, but I could be wrong. The deleteRecipe function will fire the DELETE_RECIPE reducer and remove the item from the redux store, but it will persist in Firestore.