Home > Back-end >  React.js fetch request function getting called repetedly
React.js fetch request function getting called repetedly

Time:08-27

const [notes, setNotes] = useState(notesInitial);

  //fetch notes
  const fetchNotes = async () => {
    const response = await fetch(
      "http://localhost:5500/api/notes/fetchallnotes",
      {
        method: "GET", // *GET, POST, PUT, DELETE, etc.

        headers: {
          "Content-Type": "application/json",
          "auth-token": localStorage.getItem("token"),
        },
      }
    );
    const json = await response.json();
    setNotes(json);
    console.log("Running Fetch all notes");
  };

The function fetchNotes is getting called repeatedly on sending the json to setNote. However no such thing is happening if the json is not send to the setNote.

Notes Component

const Notes = () => {
  const context = useContext(noteContext);
  const { notes, fetchNotes } = context;
  let navigate = useNavigate();

  useEffect(() => {
    if (localStorage.getItem("token")) {
      fetchNotes();
    } else {
      navigate("/login");
    }
  });

  // console.log(notes);
  return (
    <>
      <h2>All Notes</h2>
      {notes.length === 0 && "No notes. Created note will appear here"}
      {notes.map((note) => {
        return <NoteItems note={note} key={note._id} />;
      })}
    </>
  );
};

What is the possible reason for it and how can it be solved?

CodePudding user response:

You can modify the code as I'm providing and have a try,

Notes Component

const Notes = () => {
  const context = useContext(noteContext);
  const { notes, fetchNotes } = context;
  let navigate = useNavigate();
  const fetched = React.useRef(false); //  

  useEffect(() => {

    if (fetched.current === false) { //  

        if (localStorage.getItem("token")) {
          fetchNotes();
        } else {
          navigate("/login");
        }

        return () => { //  
            fetched.current = true; //  
        } //  


    } //  

  }, []); //  

  // console.log(notes);
  return (
    <>
      <h2>All Notes</h2>
      {notes.length === 0 && "No notes. Created note will appear here"}
      {notes.map((note) => {
        return <NoteItems note={note} key={note._id} />;
      })}
    </>
  );
};

CodePudding user response:

It looks to me like you just want to fetch the notes from local storage when you first load the component. You aren't specifying the second parameter in your useEffect function right now, which means notes will be fetched whenever any state changes occur in the component. If you use "[]" as the second parameter in useEffect, your notes will only be fetched when the component first loads, instead of every time the state changes.

  • Related