bernabe9 / redux-react-session

:key: Simple Session API storage for Redux and React
https://bernabe9.github.io/redux-react-session/
147 stars 41 forks source link

initSessionService should return Promise #16

Closed hitochan777 closed 6 years ago

hitochan777 commented 6 years ago

Hi. Thans for your great work! I am currently facing an issue of components trying to access session.user before it is ready to be accessed. The problem is that initSessionService calls loadUser in an async manner ( which is perfectly fine), thus, session.user can be accessed when it is not ready.

An example code is show below (Note that unimportant codes are abbreviated).

index.js

sessionService.initSessionService(store, {driver: 'COOKIES'} );
render(
    <Provider store={store}>
        <App />
    </Provider>,
    document.getElementById('root')
)

App.js

export const App = ({session}) => {
    doSomethingWithUserInfo(session.user)
    ...
}
const mapStateToProps = ({session}) => ({
    session,
});

export default connect(mapStateToProps)(App)

To avoid this problem, I want to make sure that session.user is set before proceeding to the next lines. One way to achieve this is to return Promise in initSessionService and modify refreshFromLocalStorage a bit (so that it returns the promise that corresponds to loadUser).

If you have another way of solving this issue, please let me know. Otherwise, I am willing to issue an PR! Thanks!

bernabe9 commented 6 years ago

I understand your problem and I think that the solution of returning a promise with initSessionService is the best one. Feel free to open a PR to solve this.

Another workaround could be using the variable checked in the Redux store (I think this variable is not documented, my bad :-1: ).

Try something like this:

sessionService.initSessionService(store, {driver: 'COOKIES'} );
render(
    <Provider store={store}>
        {checked && <App />}
    </Provider>,
    document.getElementById('root')
)

Anyway, your solution is much better(with a Promise). Thanks!

hitochan777 commented 6 years ago

@bernabe9 OK! I will work on that!

bernabe9 commented 6 years ago

Fixed #18