react-prefetch
v0.0.1
Published
🏃
Downloads
3
Readme
React Prefetch
Usage
import prefetch from 'react-prefetch'
const LiveItem = ({data: {pending, error, result}}) => do {
if (pending) {
<Spinner />
} else if (error) {
<Error error={error} />
} else {
<Card>{result}</Card>
}
}
export default prefetch(
props => fetch(`/lives/${props.id}`)
)(LiveItem)
Store Reducer
import {combineReducers} from 'redux'
import {reducer as prefetch} from 'react-prefetch'
export default combineReducers({
prefetch,
})
Client
import {render} from 'react-dom'
import {PrefetchProvider} from 'react-prefetch'
const store = configureStore(window[config('appStateIdentifier')])
function renderApp(App) {
const app = (
<PrefetchProvider store={store}>
<BrowserRouter>
<App />
</BrowserRouter>
</PrefetchProvider>
)
render(app, container)
}
Server
import {renderToString, renderToStaticMarkup} from 'react-dom/server'
import {PrefetchProvider, runPrefetches} from 'react-prefetch'
async function reactApp(ctx, next) {
...
const store = configureStore()
const app = (
<PrefetchProvider store={store}>
<StaticRouter>
<App />
</StaticRouter>
</PrefetchProvider>
)
// data prefetching
await runPrefetches(app)
const html = renderToStaticMarkup(
<ServerHTML
appString={renderToString(app)}
appState={{
identifier: config('appStateIdentifier'),
state: store.getState(),
}}
/>,
)
ctx.body = `<!DOCTYPE html>${html}`
...
}