I am just trying to delete an item on my page. When I delete the item I get this Unhandled Rejection (TypeError): state.recipes is undefined message pointing to my reducer. When I refresh my page, the object is gone and the error disappears. The question is what is causing this error prior to the item deleting?
This is what happens after I click delete button, when I refresh the page the object is gone.
case 'DELETING_RECIPE_START':
return {
...state.recipes,
loading: true
}
case 'DELETE_RECIPE_SUCCESS':
This line -----> const recipes = state.recipes.filter(recipe => recipe.id !== action.payload.recipeId)
return {
...state, recipes,
loading: false
}
I was told in this case is to check your delete action on the backend. When I plugged in byebug, It is showing me which object am trying to delete, so hopefully its nothing there I need to worry about.
def destroy
recipe = Recipe.find(params[:id])
unless recipe.nil?
recipe.destroy
render json: recipe
else
render json: { error: "Property not found" }, status: 404
end
end
I did modify my delete action to the thunk asynchronous conventions, and I hope it's structured correctly. I will note when I run debugger before the return(dispatch) this issue with my error seems to happen after the return(dispatch) line.
export const deleteRecipe = (recipeId) =>{
const BASE_URL = `http://localhost:3001`
const RECIPES_URL =`${BASE_URL}/recipes`
debugger
return (dispatch) => {
dispatch({ type: "DELETING_RECIPE_START" })
fetch(`${RECIPES_URL}/${recipeId}`,{method: 'DELETE'})
.then(response =>{return response.json()})
.then(recipeId => dispatch({ type: 'DELETE_RECIPE_SUCCESS', payload: recipeId }))
.catch((error) => console.log.error(error))
};
}
Last here is my Recipe component with the delete button and the event handler associated.
class Recipe extends Component {
handleOnClick(){
this.props.deleteRecipe(this.props.recipe.id);
}
render(){
return(
<div>
<h3>Name: {this.props.recipe.name}</h3>
<p>Category:{this.props.recipe.category_id}</p>
<p>Chef Name: {this.props.recipe.chef_name}</p>
<p>Origin: {this.props.recipe.origin}</p>
<p>Ingredients: {this.props.recipe.ingredients}</p>
<button onClick={()=>this.handleOnClick()}>Delete</button>
</div>
)
}
}
export default Recipe
What can I do to correct this?
question from:
https://stackoverflow.com/questions/65864841/unhandled-rejection-typeerror-state-recipes-is-undefined 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…