Home > Net >  React: Update a component's state after fetch delete
React: Update a component's state after fetch delete

Time:06-15

I am trying to update a component's state after a fetch call that deletes a row from the app's database.

I am new to react so not sure how to do this (do I need to call the get fetch event again?)

The way I am running it currently returns this error:

EditRecipe.jsx:33 Uncaught TypeError: Cannot read properties of undefined (reading 'map')

Here is my code:

export default function RecipeList() {
  const [recipes, setRecipes] = useState([])

  const recipeSetter = () => {
    fetch('/api/recipes')
      .then((res) => res.json())
      .then((data) => {
        setRecipes(data)
      })
      .catch((err) => console.log(err))
  }

  useEffect(() => {
    recipeSetter()
  }, [])

  const deleteRecipe = (e, id) => {
    console.log(id)
    e.preventDefault()
    fetch('/api/recipes/delete', {
      method: 'POST',
      headers: { 'Content-type': 'application/json' },
      body: JSON.stringify({
        id,
      }),
    }).then(() => setRecipes(recipeSetter())) //this is where the trouble is
  }

  const recipeList = recipes.map((recipe, idx) => (
    <React.Fragment key={idx}>
      <div className="recipe">
        <span>
          <Link to={'/edit/'   recipe.id}>{recipe.recipe_name}</Link>
        </span>
        <span
          className="delete"
          onClick={(evt) => deleteRecipe(evt, recipe.id)}
        >
          Delete
        </span>
      </div>
    </React.Fragment>
  ))

CodePudding user response:

recipeSetter() is a function that will re-fetch the list from the backend, it will take some time to do that fetch, and then will set the state.

Because it's asynchronous, it returns immediately, but it returns undefined (doesn't have anything that's returning)

When you call setRecipes(recipeSetter()), recipeSetter starts the fetch and returns undefined. So essentially you are calling setRecipes(undefined), which sets the state to undefined and everything blows up.

Just call recipeSetter() without the setRecipes

CodePudding user response:

It is because recipeSetter() does not return an Array. Please try the following code

  const deleteRecipe = (e, id) => {
    console.log(id)
    e.preventDefault()
    fetch('/api/recipes/delete', {
      method: 'POST',
      headers: { 'Content-type': 'application/json' },
      body: JSON.stringify({
        id,
      }),
    }).then(() => recipeSetter()) 
  }
  • Related