Subhodip Roy
Subhodip Roy

Reputation: 113

React.js fetch request function getting called repetedly

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?

Upvotes: 0

Views: 58

Answers (2)

Peter Glenn
Peter Glenn

Reputation: 11

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.

Upvotes: 1

mrasadatik
mrasadatik

Reputation: 321

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} />;
      })}
    </>
  );
};

Upvotes: 1

Related Questions