Skip to content

Instantly share code, notes, and snippets.

@mori-dev
Last active October 1, 2019 01:47
Show Gist options
  • Save mori-dev/1905603974707846e60f7d7403531b50 to your computer and use it in GitHub Desktop.
Save mori-dev/1905603974707846e60f7d7403531b50 to your computer and use it in GitHub Desktop.
redux-persist でブラウザストレージに一部のデータを保存しつつ、ストアに復旧するまで render を防ぐには
class MyAppProvider extends Component {
constructor() {
super()
this.state = { rehydratedFlag: false }
}
componentWillMount() {
appEventHandler.on(AppEvents.FINISH_REHYDRATE_STORE, () => {
this.setState({ rehydratedFlag: true });
});
}
componentWillUnmount() {
appEventHandler.removeListener(AppEvents.FINISH_REHYDRATE_STORE);
}
render() {
if (!this.state.rehydratedFlag){
return (
<MuiThemeProvider muiTheme={getMuiTheme(NowTheme)}>
<NCircularProgress />
</MuiThemeProvider>
)
}
return (
<Provider store={store}>
<MuiThemeProvider muiTheme={getMuiTheme(NowTheme)}>
<Routes />
</MuiThemeProvider>
</Provider>
)
}
}
persistStore(store, {
transforms: dataOnlyTransformFilters,
whitelist: [
'foo',
'bar',
] },
() => {
// sessionStrage への保存
persistStore(store, {
whitelist: [
'hoge',
'fuga',
],
storage: asyncSessionStorage,
},
() => {
appEventHandler.emitFinishRehydrateStore();
});
});
import EventEmitter from 'events';
import { AppEvents } from '../constants';
// USEAGE:
// const appEventHandler = new AppEventHandler();
// appEventHandler.on(AppEvents.FINISH_REHYDRATE_STORE, () => {
// // something
// });
// appEventHandler.emitFinishRehydrateStore();
//
// In react component:
// componentDidMount() {
// appEventHandler.on(AppEvents.FINISH_REHYDRATE_STORE, () => {
// // something
// });
// }
// componentWillUnmount() {
// appEventHandler.removeListener(AppEvents.FINISH_REHYDRATE_STORE);
// }
class AppEventHandler extends EventEmitter {
emitFinishRehydrateStore(): void {
this.emit(AppEvents.FINISH_REHYDRATE_STORE);
}
}
const appEventHandler = new AppEventHandler();
export default appEventHandler;
export const AppEvents = {
FINISH_REHYDRATE_STORE: 'FINISH_REHYDRATE_STORE'
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment