Doug
Doug

Reputation: 15513

Configure react redux middleware from fetch

I have a Redux middleware that requires some data to be configured via a server call (eg, fetch) which is async / requires promises.

However, every example of createStoresuch as this one seems to use a Singleton pattern for the store. This means that the store gets initialized before my fetch is complete. Because it's middleware, I can't "reconfigure" it after createStore is called.

How can i configure createStore without using a singleton pattern to configure middleware?

Upvotes: 1

Views: 260

Answers (1)

Dat Tran
Dat Tran

Reputation: 1586

How do you fetch those data? If it's just a simple API call. You can easily wait for the data to be returned then pass the data to createStore. Something like this:

const fetchData = () => {
  return Promise.resolve({
    data: 'Your data here'
  });
}

const initialState = window.__INITIAL_STATE__;
fetchData()
  .then((data) => {
    initialState.somethingYouNeed = data;
    const store = createStore(initialState);
    // Do the rest here
  });

Upvotes: 1

Related Questions