Home > Enterprise >  delete an item from a fetched data react
delete an item from a fetched data react

Time:11-19

I'm trying to delete an item from a fetched data from API, but whenever I try to press on delete button I got this error:

App.js:50          DELETE https://-api.herokuapp.com/api/products/{id} 404 (Not Found)

Here is my code:

const deleteProduct = async (id) => {
  await fetch(
    `https://upayments-studycase-api.herokuapp.com/api/products/{id}`,
    { method: "DELETE" }
  );
  setProdcts(products.filter((product) => product.id !== id));
};

return(
  <div key={product.id}>
    <div>
      <div>
        <FaTimes
          onClick={() => onDelete(product.id)}
        />
        <p>{product. Price}</p>{" "}
      </div>
)

a photo of the error:

enter image description here

the code is in sandbox code So what happens after clicking on the delete sign it deleted all the items from the page, and then it re-loaded them.

I want to delete a specific item from the data.

CodePudding user response:

You're missing a $ in your template literal, so the id variable can be substituted:

`https://upayments-studycase-api.herokuapp.com/api/products/${id}`

More info here

CodePudding user response:

make sure to add "$" as the above answers and you should use backticks `` for string templating and not simple '' or double quotes "".

check the following issue on stackoverflow: https://stackoverflow.com/a/53994397/8808725

CodePudding user response:

Another response with a formated code for visibility

const deleteProduct = async (id) => {     
    await fetch(
       `upayments-studycase-api.herokuapp.com/api/products/${id}`, 
       { method: "DELETE" }
    )
    .then(() => {      
       return setProducts(products.filter(product => product.id !== id))   
    })     
}; 
  • Related