Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple fetch data axios with React Hooks

I would like to get global information from Github user and his repos(and get pinned repos will be awesome). I try to make it with async await but It's is correct? I've got 4 times reRender (4 times console log). It is possible to wait all component to reRender when all data is fetched?

function App() {
  const [data, setData] = useState(null);
  const [repos, setRepos] = useState(null);

  useEffect(() => {
    const fetchData = async () => {
      const respGlobal = await axios(`https://api.github.com/users/${username}`);
      const respRepos = await axios(`https://api.github.com/users/${username}/repos`);

      setData(respGlobal.data);
      setRepos(respRepos.data);
    };

    fetchData()

  }, []);

  if (data) {
    console.log(data, repos);
  }

  return (<h1>Hello</h1>)
}
like image 968
Direct 96 Avatar asked Apr 04 '19 17:04

Direct 96


People also ask

How fetch multiple API in React using Axios?

First, we import axios and define the API/URL we want to load from. After that, we define that we want to perform a GET request using axios on the above URL. const requestOne = axios. get(one);

Can you have multiple componentDidMount?

React components call componentDidMount only once by default. You can run the component multiple times if you delete the component or change the props or state.


1 Answers

Multiple state updates are batched but but only if it occurs from within event handlers synchronously and not setTimeouts or async-await wrapped methods.

This behavior is similar to classes and since in your case its performing two state update cycles due to two state update calls happening

So Initially you have an initial render and then you have two state updates which is why component renders three times.

Since the two states in your case are related, you can create an object and update them together like this:

function App() {
  const [resp, setGitData] = useState({ data: null, repos: null });

  useEffect(() => {
    const fetchData = async () => {
      const respGlobal = await axios(
        `https://api.github.com/users/${username}`
      );
      const respRepos = await axios(
        `https://api.github.com/users/${username}/repos`
      );

      setGitData({ data: respGlobal.data, repos: respGlobal.data });
    };

    fetchData();
  }, []);

  console.log('render');
  if (resp.data) {
    console.log("d", resp.data, resp.repos);
  }

  return <h1>Hello</h1>;
}

Working demo

like image 161
Shubham Khatri Avatar answered Oct 11 '22 11:10

Shubham Khatri