简体   繁体   中英

how get new data from database in reactjs

My projct is a note app where you can can add notes and delete notes. I want to get data from the database and show it but I have to delete note twice, add note or reload page to show the new data.

notesList.jsx
this is my main component
i send getNotes() to another component for i can get new datas

const NotesList = () => {
  const [notes, setNotes] = useState([]);

  const getNotes = async () => {
    const getNoteInformation = {
      email: localStorage.getItem("tokenEmail"),
    };
    const response = await axios.post(
      "http://localhost:9000/api/note/get",
      getNoteInformation
    );
    try {
      setNotes(response.data.data);
    } catch (error) {}
  };

  const handleAddNote = async (tasktext) => {
    const addNoteInformation = {
      email: localStorage.getItem("tokenEmail"),
      taskText: tasktext,
      date: moment(new Date()).locale("fa").format("YYYY/MM/DD").toString(),
    };

    if (addNoteInformation.email && addNoteInformation.taskText) {
      try {
        await axios.post(
          "http://localhost:9000/api/note/add",
          addNoteInformation
        );
      } catch (error) {}
    }
  };

  const handleDeleteNote = async (id) => {
    const deletedInformaion = {
      email: localStorage.getItem("tokenEmail"),
      noteId: id,
    };

    if (deletedInformaion.email && deletedInformaion.noteId) {
      await axios.post(
        "http://localhost:9000/api/note/deleted",
        deletedInformaion
      );
    }
  };

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

  return (
    <>
      <Navbar />
      <div className="container">
        <div className="row">
          {notes
            .filter((notes) => notes != null)
            .map((notes, index) => (
              <Note
                key={index}
                text={notes.text}
                date={notes.date}
                id={notes._id}
                deletenote={handleDeleteNote}
                getnote={getNotes}
              />
            ))}
          <AddNote getnote={getNotes} addnote={handleAddNote} />
        </div>
      </div>
    </>
  );
};

note.jsx

const Note = (props) => {
  const handleDeleteNote =  () => {
    props.deletenote(props.id);
    props.getnote();
  };

  return (
    <>
      <div className="col-lg-4 col-md-6 col-sm-12 p-4">
        <div className="note d-flex flex-column">
          <span className="note-top overflow-auto m-2 ps-2">{props.text}</span>
          <div className="note-bottom d-flex justify-content-between flex-row-reverse mt-auto">
            <small>{props.date}</small>
            <MdDelete
              onClick={handleDeleteNote}
              className="delete-icon"
              size="1.3rem"
              color="#bb86fc"
            />
          </div>
        </div>
      </div>
    </>
  );
};

addNote.jsx

const AddNote = (props) => {
  let addNoteText = useRef();

  const handleAddNote = async () => {
    props.addnote(addNoteText.current.value);
    props.getnote();
    addNoteText.current.value = "";
  };

  return (
    <div className="col-lg-4 col-md-6 col-sm-12 p-4">
      <div className="add-note-box d-flex flex-column justify-content-between">
        <div className="top-box">
          <textarea
            placeholder="یادداشت خود را وارد کنید ......"
            class="form-control"
            rows={7}
            ref={addNoteText}
          ></textarea>
        </div>
        <BsFillPlusCircleFill
          onClick={handleAddNote}
          className="plus-icon"
          size="1.3rem"
          color="#bb86fc"
        />
      </div>
    </div>
  );
};

You didn't update state after sending the respective add and delete request, that's why you need to refresh to get the updated data. This is the fix:

  const handleAddNote = async (tasktext) => {
    const addNoteInformation = {
      email: localStorage.getItem("tokenEmail"),
      taskText: tasktext,
      date: moment(new Date()).locale("fa").format("YYYY/MM/DD").toString(),
    };

    if (addNoteInformation.email && addNoteInformation.taskText) {
      try {
        await axios.post(
          "http://localhost:9000/api/note/add",
          addNoteInformation
        );
     
        setNotes([...notes, addNoteInformation]); // update state using spread operator and put the new one to the end
      } catch (error) {}
    }
  };

  const handleDeleteNote = async (id) => {
    const deletedInformaion = {
      email: localStorage.getItem("tokenEmail"),
      noteId: id,
    };

    if (deletedInformaion.email && deletedInformaion.noteId) {
      await axios.post(
        "http://localhost:9000/api/note/deleted",
        deletedInformaion
      );
      
      setNotes(notes.filter(note => note.id !== id)) // update state using filter function
    }
  };

Alternativelly, when adding notes, you can update state using the response object from your request, since the id of newly created note maybe generated by your database. It dependes on the actual response object from the axios request:

const response = await axios.post();
setNotes([...notes, response.data]);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM