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?
Notefunction is getting called repeatedly and hence the useState. The thing is happening only on sending the json to setNote else not.useEffectthen 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.