简体   繁体   中英

API is getting called over and over again when I am using react hooks

I am using React Hooks to get data from an existing API. Here is my code

import React, { useState, useEffect } from "react";

export const People = () => {
  const [people, setPeople] = useState([]);
  const url = "http://127.0.0.1:5000/people";

  async function fetchData() {
    console.log("calling api .. ");
    const res = await fetch(url);
    res.json().then((res) => setPeople(res));
  }

  useEffect(() => {
    fetchData();
  });

  return (
    <div>
      <ul>
        {people &&
          people.map((person) => <li key={person.id}>{person.name}</li>)}
      </ul>
    </div>
  );
};

const Dashboard = (props) => {
  return (
    <div>
      <People />
    </div>
  );
};

export default Dashboard;

The problem that I am having is this API is getting called over and over again. Can you please let me know what I am doing wrong here.

Thanks

Currently, using useEffect(callback) will execute the callback on every render .

Try using useEffect with an empty dependencies array .

If you want to run an effect and clean it up only once , you can pass an empty array ( [] ) as a second argument. This tells React that your effect doesn't depend on any values from props or state, so it never needs to re-run .

  • Check my other answer on useEffect use cases.
useEffect(() => {
  fetchData();
}, []);

As for the rest of the component, it should look like so (opinioned):

// Should be on the outer scope as the URL is decoupled from the component's logic
const url = "http://127.0.0.1:5000/people";

export const People = () => {
  const [people, setPeople] = useState([]);

  useEffect(() => {
  // This way fetchData won't re-assigned on every render
    async function fetchData() {
      console.log("calling api .. ");
      const res = await fetch(URL);

      // Consitstance, don't mix `then` and `await` syntax
      const people = await res.json();
      setPeople(people);
    }

    fetchData();
  }, []);

  return (
    <div>
      <ul>
        {people &&
          people.map((person) => <li key={person.id}>{person.name}</li>)}
      </ul>
    </div>
  );
};

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM