Server-side rendering
There's a good chance you're using React with Server-side rendering (SSR), as many applications require this to be successful. If you happen to be using Next.js, it's really easy to integrate React Async. The crux is in setting a initialValue, which is fetched server-side for initial page loads and passed along through rehydration.
1
import fetch from "isomorphic-unfetch"
2
3
const fetchPerson = async ({ id }) => {
4
const response = await fetch(`https://swapi.co/api/people/${id}/`)
5
if (!response.ok) throw new Error(response.status)
6
return response.json()
7
}
8
9
const Person = ({ id, person }) => (
10
<Async promiseFn={fetchPerson} initialValue={person} id={id}>
11
<Async.Pending>Loading...</Async.Pending>
12
<Async.Rejected>{error => <ErrorMessage {...error} />}</Async.Rejected>
13
<Async.Fulfilled>{data => <Greeting {...data} />}</Async.Fulfilled>
14
</Async>
15
)
16
17
Person.getInitialProps = async ({ req }) => {
18
const id = req.params.id
19
const person = await fetchPerson({ id })
20
return { id, person }
21
}
Copied!
If React Async is provided an initialValue, it will not invoke the promiseFn on mount. Instead it will use the initialValue to immediately set data or error, and render accordingly.
Last modified 2yr ago
Copy link