PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Thursday, October 13, 2022

[FIXED] When I first click the delete button, all the notes are disappeared but, when I refresh the page it works just fine

 October 13, 2022     axios, express, javascript, mongoose, reactjs     No comments   

Issue

I tried almost everything. I tested my API to ensure that the problem is not with it. It happens just one time when you visit the page. However, when you refresh it works fine.

Before Clicking delete: Click here to see the image

After clicking delete button: Click here to see the image

Backend Route (home.route.js):

const express = require("express");
const mongoose = require("mongoose");
const Note = require("../models/note.model.js");
const router = express.Router();

router.get("/", (req, res) => {
    Note.find()
        .then(notes => res.json(notes))
        .catch(err => res.status(400).json("Error: " + err));
});

router.post("/", (req, res) => {
    const note = req.body;
    const newNote = new Note(note);

    newNote.save()
        .then(() => res.json("Note added"))
        .catch(err => res.status(400).json("Error: " + err));
});

router.delete("/", (req, res) => {
    const idWeGotFromReact = req.body.noteId;
    Note.findByIdAndDelete(idWeGotFromReact)
        .then(() => res.json('Note deleted.'))
        .catch(err => res.status(400).json('Error: ' + err));
})

module.exports = router;

React Code:

Code for the Note Component:

import React from "react";
import axios from 'axios';
import DeleteIcon from '@material-ui/icons/Delete';

function Note(props) {
  function handleClick() {
    const id = props.noteId;
    axios({
      method: 'delete',
      url: 'http://localhost:5000',
      data: {
        noteId: id
      }
    });
    props.onDelete(id);
  }

  return (
    <div className="note">
      <h1>{props.title}</h1>
      <p>{props.content}</p>
      <button name={props.noteId} onClick={handleClick}>
        <DeleteIcon />
      </button>
    </div>
  );
}

export default Note;

Code for the Main App component:

import React, { useState, useEffect } from "react";
import axios from "axios";
import Header from "./Header";
import Footer from "./Footer";
import Note from "./Note";
import CreateArea from "./CreateArea";

function App() {
  const [notes, setNotes] = useState([]);

  useEffect(() => {
    axios
      .get('http://localhost:5000')
      .then(res => {
        setNotes(res.data);
      });
  }, []);


  function addNote(newNote) {
    setNotes(prevNotes => {
      return [...prevNotes, newNote];
    });
  }


  function deleteNote(id) {
    setNotes(notes => {
      return notes.filter((noteItem) => {
        return noteItem._id !== id;
      });
    });
  }

  function NoteList() {
    return (
      notes.map((noteItem) => {
        return (
          <Note
            key={noteItem._id}
            id={noteItem._id}
            title={noteItem.title}
            content={noteItem.content}
            onDelete={deleteNote}
            noteId={noteItem._id}
          />
        );
      })
    );
  }

  return (
    <div>
      <Header />
      <CreateArea onAdd={addNote} />
      <NoteList />
      <Footer />
    </div>
  );
}

export default App;

Input Component:

import React, { useState } from "react";
import axios from "axios";

function CreateArea(props) {
  const [note, setNote] = useState({
    title: "",
    content: ""
  });

  function handleChange(event) {
    const { name, value } = event.target;

    setNote(prevNote => {
      return {
        ...prevNote,
        [name]: value
      };
    });
  }

  function submitNote(event) {
    props.onAdd(note);
    setNote({
      title: "",
      content: ""
    });

    event.preventDefault();

    axios
      .post('http://localhost:5000', note)
      .then(res => {
        console.log(res);
        console.log(res.data);
      });
  }

  return (
    <div>
      <form action="/" method="post">
        <input
          name="title"
          onChange={handleChange}
          value={note.title}
          placeholder="Title"
        />
        <textarea
          name="content"
          onChange={handleChange}
          value={note.content}
          placeholder="Take a note..."
          rows="3"
        />
        <button className="button" onClick={submitNote}>Add</button>
      </form>
    </div>
  );
}

export default CreateArea;

I would also appreciate if you can provide a review of my code because I am a beginner and that would definitely help me.


Solution

Try this approach, (just an assumption)

  function deleteNote(id) {
    setNotes(notes => {
      const filteredNotes =  notes.filter((noteItem) => {
        return noteItem._id !== id;
      });
      return [...filteredNotes];
    });
  }


Answered By - Sarun UK
Answer Checked By - Marie Seifert (PHPFixing Admin)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing