0

I tried to delete the item >>But when I click on the button and function does not work!!!!

Deleting in backend works but in frontend does not work!!

This is my function:

deleteblog = async id => {
        // this.setState({ isLoading: true });
        try {
          const response = await fetch(
            `http://localhost:8080/blog/delete/${id}`
          );

          const answer = await response.json();
          if (answer.success) {
            const blog = this.state.blog.filter(
              contact => contact.id !== id
            );
            toast(`blog with id ${id} was successfully deleted!`);
            this.setState({ blog });
          } else {
            console.log();
           false });
          }
        } catch (err) {
          console.log("error", err);
         false });
        }
      };

This is the button:

<button type="button" onClick={this.deleteblog} class="btn btn-danger btn-rounded btn-sm my-0">delete</button>

This error that is showed in console log

GET http://localhost:8080/blog/delete/undefined 500 (Internal Server Error)
 error SyntaxError: Unexpected token < in JSON at position 0
    at BlogAdmin.deleteblog (Blogadmin.js:104)

And this >>> Blogadmin.js:104

====> const answer = await response.json();
DarkRob
  • 3,843
  • 1
  • 10
  • 27
amani rose
  • 121
  • 1
  • 9

1 Answers1

0

The response might be an HTML instead of a JSON response, it is better to have more check than accessing response.json() directly as that will be dangerous and easily throw you a Syntax Error.

You can check the response through the browser development console -> Network tab, and see the request and response:

enter image description here

or adding console.log to the response for debugging.

After all, you should improve the handling for reading the response data, and your application will be fine:

deleteblog = async id => {
  this.setState({ isLoading: true });

  try {
    const response = await fetch(`http://localhost:8080/blog/delete/${id}`);

    // For debugging
    console.log('response', JSON.stringify(response));

    const answer = response && typeof response.json === 'function' && response.json();

    if (answer.success) {
      const blog = this.state.blog.filter(contact => contact.id !== id);
      toast(`blog with id ${id} was successfully deleted!`);
      this.setState({ blog });
    }
    else {
      toast(`Error: blog with id ${id} was unable to delete!`);
      this.setState({ isLoading: false });
    }
  }
  catch (err) {
    console.error('Unexpected error occurred:', err);
    this.setState({ isLoading: false });
  }
};
Jee Mok
  • 6,157
  • 8
  • 47
  • 80