Redux - Loading initial state asynchronously

前端 未结 3 705
遥遥无期
遥遥无期 2021-02-19 02:48

I\'m trying to work out the cleanest way to load the initial state of my Redux stores when it comes from API calls.

I understand that the typical way of providing the in

3条回答
  •  攒了一身酷
    2021-02-19 02:57

    My app startup workflow:

    1. Loading spinner in index.html
    2. Ajax to check if user is logged in
    3. On ajax end, render the Root component
    4. Hide the loading spinner

    I achieved that by:

    1. Creating the store with a custom middleware that listens for the initial ajax end action and calls a callback once
    2. Dispatching the initial ajax action

    root.js

    const store = createStore(
        rootReducer,
        applyMiddleware(
            ...,
            actionCallbackOnceMiddleware(INITIAL_AJAX_END, render)
        )
    )
    
    function render() {
        ReactDOM.render(
            
                
            ,
            document.getElementById('root')
        )
    
        document.getElementById('loading').dispatchEvent(new Event('hide'))
    }
    
    store.dispatch(initialAjaxAction());
    

    middleware/actionCallbackOnce.js

    export default (actionType, callback) => store => next => {
        let called = false;
    
        return action => {
            next(action);
    
            if (!called && action.type === actionType) {
                called = true;
                callback();
            }
        }
    }
    

    index.html

    Loading

提交回复
热议问题