Hazal Kaya
Hazal Kaya

Reputation: 671

delete an item from a fetched data react

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/%7Bid%7D 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.

Upvotes: 0

Views: 764

Answers (4)

Maniraj Murugan
Maniraj Murugan

Reputation: 9084

One of the issue is that you are using the template literal string, so to include dynamic value, you need to add ${id}

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

Another issue is that the error happen due to misspell of the id.

Based on the update in the question, actual property name is _id and not id.

Forked example

Edit new-cdn-64b59u

Upvotes: 1

Mohamed CHIBANI
Mohamed CHIBANI

Reputation: 156

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))   
    })     
}; 

Upvotes: 0

Mohamed CHIBANI
Mohamed CHIBANI

Reputation: 156

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

Upvotes: 0

rocambille
rocambille

Reputation: 15996

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

Upvotes: 1

Related Questions