Loading data from a remote server using vanilla Next.js
Let's begin with a quick explanation of how data is usually loaded in traditional React apps.
If you don't use any data management frameworks, then your best bet is to request data when the component will mount, as shown here:
class Foo extends React.Component { state = {data: null}; loadData = async () => await (await fetch('...')).json(); async componentWillMount(){ const data = await this.loadData(); this.setState({data}); } render(){ if (!this.state.data) return (<div>Loading...</div>); return (<pre>{JSON.stringify(this.state.data)}</pre>); } }
This will initiate the data loading process when the component is about to be mounted. Before the data is made available, it will show a loading indicator.
Note
Unfortunately, this will not work in a server environment during server-side rendering, because the server will not know that it should wait for data to arrive, so it will always...