0
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?

6
  • "The function fetchNotes is getting called repeatedly" - What calls the function at all? You're showing code which defines the function, but nothing here ever invokes it... Commented Aug 26, 2022 at 17:19
  • May be you call this fetchNotes function in the useEffect and the dependecy is notes. in this case fetchNotes function call repeatedly. can you please share your useEffect code ? Commented Aug 26, 2022 at 17:24
  • @ShubhamJasani Yes I am calling it in useEffect, I have added the part in the question. I also discovered that whole Note function is getting called repeatedly and hence the useState. The thing is happening only on sending the json to setNote else not. Commented Aug 26, 2022 at 17:41
  • Does this answer your question? Why useEffect runs every time when component re-render? Commented Aug 26, 2022 at 17:46
  • Short version... If you omit the second argument to useEffect then it will execute on every render. To only execute it on the first render, pass an empty dependency array. To execute it any time a dependency changes, include that dependency in the array. Commented Aug 26, 2022 at 17:47

2 Answers 2

1

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} />;
      })}
    </>
  );
};
Sign up to request clarification or add additional context in comments.

Comments

1

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.