JangoCG
JangoCG

Reputation: 976

Trigger useEffect again after API call

I have the following useEffect hook which runs on the initial loading of the page

useEffect(() => {
  const getLeads = () => axios.get("/api/leads");

  const setLeadState = async () => {
    try {
      const res = await getLeads();
      res.data.map(lead => setLeads(prevState => [...prevState, lead]));
    } catch (err) {
      console.error(err);
    }
  };
  setLeadState();
}, []);

and then I have the following function to add new data to the api. This function is called on a form submit.

const addLead = async (firstName, lastName, email) => {
  try {
    const body = {
      firstName,
      lastName,
      email
    };
    const res = await axios.post("api/leads", body);
  } catch (err) {
    console.error(err);
  }
};

How can I call my useEffect hook again after the addLead function was executed? I tried something like this

const [test, setTest] = useState("");

useEffect(() => {
  const getLeads = () => axios.get("/api/leads");

  const setLeadState = async () => {
    try {
      const res = await getLeads();
      res.data.map(lead => setLeads(prevState => [...prevState, lead]));
    } catch (err) {
      console.error(err);
    }
  };
  setLeadState();
}, [test]);

And then changed "test" in the addLead function, however this leads to an infinite loop with the page not rendering at all.

Upvotes: 0

Views: 1057

Answers (1)

Jap Mul
Jap Mul

Reputation: 18759

Move the function that fetches/sets the data outside of the effect and then call that function after addLead

const getLeads = () => axios.get("/api/leads");

const setLeadState = async () => {
  try {
    const res = await getLeads();
    res.data.map(lead => setLeads(prevState => [...prevState, lead]));
  } catch (err) {
    console.error(err);
  }
};

// Initial load
useEffect(() => {
  setLeadState();
}, []);

const addLead = async (firstName, lastName, email) => {
  try {
    const body = {
      firstName,
      lastName,
      email
    };
    const res = await axios.post("api/leads", body);
    // Load again
    setLeadState();
  } catch (err) {
    console.error(err);
  }
};

Upvotes: 1

Related Questions