score:31

Accepted answer

It's because no callback function is being passed into useEffect. In the example above, it is actually executing the fetch request which doesn't return anything. Wrap the fetch call in an arrow/anonymous function and it will work.

function App() {
  const [user, setUser] = React.useState(null);
  React.useEffect(() => { // Pass in a callback function!
    fetch('https://randomuser.me/api/')
      .then(results => results.json())
      .then(data => {
        setUser(data.results[0]);
    });
  }, []);
  
  return <div>
    {user ? user.name.first : 'Loading...'}
  </div>;
}

ReactDOM.render(<App/>, document.getElementById('app'));
<script src="https://unpkg.com/react@16.7.0-alpha.0/umd/react.development.js"></script>
<script src="https://unpkg.com/react-dom@16.7.0-alpha.0/umd/react-dom.development.js"></script>

<div id="app"></div>

score:1

useEffect must have a callback function. In this case you can use an arrow/anonymous function inside the brackets. useEffect(()=>{your code})


Related Query

More Query from same tag