DavTheDev20
DavTheDev20

Reputation: 31

.then promise not working within axios delete request in react application

I am trying to call a function to fetch data from the database upon deleting a note. This is so that the array of notes can be updated to reflect the deleted note. The function where the error occurs is called deleteNote and the function I am trying to call within the .then promise is getNotes. Below is the code in my App.js file. If someone could help me solve this I'd greatly appreciate it.

import React, { useEffect, useState } from 'react';
import axios from 'axios';
// import HighlightOffIcon from '@material-ui/icons/HighlightOff';
import './App.css';

const App = () => {

  const [note, setNote] = useState('');
  const [notesList, setNotesList] = useState([]);

  const getNotes = () => {
    axios.get('http://localhost:8080/api')
      .then((res) => setNotesList(res.data))
      .catch(() => alert('Error recieving data.'));
  }

  useEffect(() => {
    getNotes();
  }, [])

  const handleChange = (event) => {
    const content = event.target.value;
    setNote(content);
  }

  const handleSubmission = (event) => {
    event.preventDefault();

    axios({
      url: 'http://localhost:8080/api/save',
      method: 'POST',
      data: {
        content: note
      }
    })
      .then((res) => {
        console.log('Created Note');
        setNote('');
        getNotes();
      })
      .catch(() => {
        console.log('Internal server error');
      })
  }

  const deleteNote = (event) => {
    const value = event.target.value;
    axios({
      method: 'DELETE',
      url: 'http://localhost:8080/api/delete',
      data: {
        _id: value
      }
    })
      .then(() => {
        console.log('Note Deleted');
        getNotes(); //Where the notes should be fetched upon successful deletion.
      })
      .catch(() => {
        alert('Error deleting note.');
      });
  }

  return (
    <div className="app">
      <h1>React Notes App</h1>
      <form onSubmit={handleSubmission}>
        <input
          type="text"
          placeholder="Enter note"
          value={note}
          onChange={handleChange}
        />
        <button className="submit-button">Submit</button>
      </form>
      <div className="notes-list">
        {notesList.map((note, index) => {
          return (
            <div className="note" key={index}>
              <p>{note.content}</p>
              <button value={note._id} className="delete-button" onClick={deleteNote}><i className="fas fa-trash-alt"></i></button>
            </div>

          );
        })}
      </div>
    </div>
  );
}

export default App;

Upvotes: 2

Views: 1108

Answers (1)

DavTheDev20
DavTheDev20

Reputation: 31

I figured out the issue. When sending a request with axios, you must have a response sent back from the server in order to execute any code you may have in the promise.

example server code:

app.delete('/delete', (req, res) => {
BlogPost.delete({_id: req.body.id}, (err) => {
if (err) {
console.log(err);
} else {
console.log('Successfully deleted blog post.')
res.json({ //Must include a response to execute code within the axios promise.
msg: 'Delete request was recieved.'
}); 
}
});
});

Upvotes: 1

Related Questions