Multiple fetch data axios with React Hooks

前端 未结 4 1979
忘掉有多难
忘掉有多难 2021-01-03 13:53

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 go

4条回答
  •  庸人自扰
    2021-01-03 14:18

    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 liek

    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 

    Hello

    ; }

    Working demo

提交回复
热议问题