Load data for components before router transition.
npm i --save react-router-prefetch
For prefetching enable you need only 2 steps:
- Add static method prefetch to your component that returns a Promise
// component.jsx
import React, ( Component ) from 'react';
let asyncData = {};
class MyComponent extends Component {
static prefetch(props) {
return new Promise((resolve) => {
fetch(`/data/${props.id}`)
.then(data => {
asyncData = data;
resolve();
});
});
}
render() {
const { foo, bar } = asyncData;
...
}
}
- Wrap Router childs in a component Prefetch from this package
export default MyComponent;
// routes.jsx
import { BrowserRouter as Router } from 'react-router';
import Prefetch from 'react-router-prefetch';
import Routes from '...';
const App = (history) => (
<Router history={history}>
<Prefetch
onError={message => window.alert(message)}
>
<Routes />
</Prefetch>
</Router>
)
export default App;
- Same as previous example, but prefetch method should be created by
createSagaPrefetch
// component.jsx
import React, ( Component ) from 'react';
import { createSagaPrefetch } from 'react-router-prefetch';
import { connect } from 'react-redux';
class MyComponent extends Component {
static prefetch = props => createSagaPrefetch({
props,
'ACTION_TYPE',
// payload
{
key: props.id,
},
})
render() {
...
}
}
export default connect()(MyComponent);
- Add handler into your saga
// sagas.js
import { call, put } from 'redux-saga/effects';
import api from './api';
import types from './types';
function* fetchData({ payload, resolve, reject }) {
try {
const data = yield call(api, payload);
yield put({
type: types.DATA_SUCCESS,
payload: data,
});
resolve();
} catch (e) {
yield put({
type: types.DATA_FAILURE,
payload: e,
});
reject(e);
}
}
# | Name | Description |
---|---|---|
1 | props | Properties of Component - it used for get and call dispatch from it |
2 | type | action.type that would be passed to dispatch |
3 | payload | action.payload that would be passed to dispatch |
Name | Type | Required | Default | Description |
---|---|---|---|---|
initialHide | bool |
true | Hide children on initial transition | |
errorMessage | string |
'Error while page loading' | Message for Promise rejecting callback | |
prefetchMethod | string |
'prefetch' | Name of method that Prefetch will recursively search in children | |
preloader | node |
'Loading...' | String or Component displays while fetching | |
onError | func |
+ | Promise reject callback | |
onFetchStart | func |
Callback before prefetch | ||
onFetchEnd | func |
Callback after prefetch or reject |
Feel free to open issues