how to call api on load using hooks in react

Solutions on MaxInterview for how to call api on load using hooks in react by the best coders in the world

showing results for - "how to call api on load using hooks in react"
Tony
04 Mar 2020
1function User() {
2  const [firstName, setFirstName] = React.useState(null);
3  const [lastName, setLastName] = React.useState(null);
4  
5  React.useEffect(() => {
6    fetch('https://randomuser.me/api/')
7      .then(results => results.json())
8      .then(data => {
9        const {name} = data.results[0];
10        setFirstName(name.first);
11        setLastName(name.last);
12      });
13  }, []); // <-- Have to pass in [] here!
14
15  return (
16    <div>
17      Name: {!firstName || !lastName ? 'Loading...' : `${firstName} ${lastName}`}
18    </div>
19  );
20}
21
22ReactDOM.render(<User />, document.querySelector('#app'));