reactjs - defaultState of Redux store from API -
how can make default state of redux store data comes in api request?
i want make request this, pass returned data defaultstate
when creating store:
const request = new xmlhttprequest(); request.open('get', '/api', true); request.onload = function load() { if (this.status >= 200 && this.status < 400) { const data = json.parse(this.response); } else { // reached our target server, returned error } }; const store = createstore(rootreducer, defaultstate, enhancers);
if you'd set asynchronously loaded state default, should try loading before starting application in index.js
:
import reducer './reducer'; function asyncstateloadingfunction(callback) { const request = new xmlhttprequest(); request.open('get', '/api', true); request.onload = function load() { if (this.status >= 200 && this.status < 400) { callback(json.parse(this.response)); } else { callback(null, 'error occured'); } }; }; promise((resolve, reject) => { asyncstateloadingfunction((result) => { resolve(result); }, (error) => { throw new error(error); }); }) .then((initialstate) => { // note create redux store, routers etc const store = createstore(reducer, initialstate); reactdom.render( <provider store={store}> <app /> </provider>, document.queryselector('#app') ); });
Comments
Post a Comment