How do I call a function automatically when page loads up in React JS ?(in 2020)

Viewed 9627

I am trying to get the array of Notes from MongoDB server example of the notes array is as shown

{
    "_id" : ObjectId("5f240b9ab414f1377c4155e0"),
    "title" : "Hello",
    "content" : "World !",
    "__v" : 0
}

/* 2 */
{
    "_id" : ObjectId("5f240d45b414f1377c4155e1"),
    "title" : "aaaaaaaaaa",
    "content" : "aaa",
    "__v" : 0
}

Now the Function getNote gets the note from MongoDB and then using useState I am passing the array , Now my question is: I want the function getNote to be called automatically when React Page loads up .Below is the code for function getNote

function getNote() {
    axios
      .get("/")
      .then((response) => {
        setFinalNoteDB(response.data);
        
      })
      .catch((err) => {
        if (err) {
          console.log("error in app.jsx");
        }
      });

The general app.jsx code is as shown below

import React, { useState, Component } from "react";
import Header from "./Header";
import CreateArea from "./CreateArea";
import Footer from "./Footer";
import Note from "./Note";
import EnterNameTemplate from "./EnterNameTemplate";
import axios from "axios";

function App() {
  const [finalNote, setFinalNote] = useState([]);
  const [finalNoteDB, setFinalNoteDB] = useState([]);
  // const [isNameThere, setIsNameThere] = useState(false);
  function addNote(note) {
    setFinalNote((prevNotes) => {
      return [...prevNotes, note];
    });
  }
  function deleteNote(id) {
    setFinalNote((prevNotes) => {
      return prevNotes.filter((singleNote, index) => {
        return index !== id;
      });
    });
  }
  function getNote() {
    axios
      .get("/")
      .then((response) => {
        setFinalNoteDB(response.data);
        
      })
      .catch((err) => {
        if (err) {
          console.log("error in app.jsx");
        }
      });
  }
  return (
    <div>
      <Header />
      <CreateArea addNote={addNote} />
      {finalNoteDB.map((singleNote, index) => {
        return (
          <Note
            key={index}
            id={index}
            title={singleNote.title}
            content={singleNote.content}
            deleteNote={deleteNote}
          />
        );
      })}

      <Footer />
    </div>
  );
  
}

export default App;

Hope you get my question ! .

2 Answers

You can use useEffect hook. Like this

 useEffect(() => {
let ignore = false;

if (!ignore)  getNote()
return () => { ignore = true; }
},[]);

I have used the ignore variable to ensure it doesn't call the function each time the component re-renders.

You could use an useEffect hook. When you run it without arguments it acts as a componentDidMount() life-cycle hook. Just add this above the return statement in you app component.

useEffect(() => {
  getNote();
}, []);
Related