Redux - Loading initial state asynchronously

前端 未结 3 671
遥遥无期
遥遥无期 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 03:09

    As far as I can tell, you have only two options (logically):

    1. Set the initial state after the store is instantiated
    2. Set the initial state when the store is instantiated

    Option 1 must be done using an action:

    The only way to change the state is to emit an action, an object describing what happened.

    — One of "Three Principles" in the docs

    This is what you've tried, but you think it is crude for some reason.


    The alternative is just to call createStore after your asynch request has resolved. One solution has already been posted (by @Gaurav Mantri) using a Promise object, which is a nice approach.

    I would recommend against this, since you will likely have multiple modules trying to require or import your store (or store.dispatch, or store.subscribe) before it exists; they would all have to be made to expect Promises. The first method is the most Redux-y.

提交回复
热议问题