reactjs
Redux state not updating right away?
setCurrentPage just stores the object into a page object in my global store. so if i try to access it RIGHT after i set it.. it seems like there's a delay and the object is empty. but if i console.log the same object in a button after and click it.. it's populated. is there a lag in redux that I dont know about? what can I do to get this to work? it's messing up my code... thanks for any help // initialState.js // my global redux store playlist: { currentPage: {} } // someComponent let tempPage = new Page(); tempPage.controlNode = someAPItoGetControlNode(); //synchronous this.props.actions.setCurrentPage(tempPage); //tempPage.controlNode contains object correctly console.log(this.props.currentPage); //empty object. WHY??? // in some function in the same component i call in a button function seeCurrentPage() { console.log(this.props.currentPage); //works! } // reducer case types.SET_CURRENT_PAGE: { action.pageObj.selected = true; return Object.assign({}, state, {currentPage: action.pageObj}); } // action export function setCurrentPage(pageObj) { return { type: types.SET_CURRENT_PAGE, pageObj: pageObj }; }
The reason for a delayed information is not because of redux, but because of the asynchronous execution of your component. // someComponent let tempPage = new Page(); tempPage.controlNode = someAPItoGetControlNode(); //synchronous this.props.actions.setCurrentPage(tempPage); //tempPage.controlNode contains object correctly console.log(this.props.currentPage); In the above code, your component fires an action and then immediately after logs this.props.currentPage. However by that time the redux store would not have updated and hence you get an older result What you can do is log in the componentWillReceiveProps function like componentWillReceiveProps(nectProps) { console.log(nextProps.currentPage) }
After the Redux store is updated, your component will need to re-render. So you can just write the console.log in componentWillReceiveProps(nextProps) or componentDidUpdate(), then you can access to the new data from the store.
Related Links
ReactJs - How to get updated state while inside a thunk promise
Syntax error on comonent proxy
TypeScript custom declaration files for untyped npm modules
React native ex-navigation chnaging routers
React and Authorization using an API
electron not allowed to load local resource
How to use jsx-control-statements in reactjs?
Leaflet with Webpack: error in css-loader
React - Where should I load async data?
Infinite componentDidUpdate() calls with react-router
How to ignore .d.ts file inside npm package?
Using goBack function from react-router-redux
Can I create alias routes using react router?
Unable to update the state of my app, console.log inside reducer shows that object has changed, but the state remains same
Change background of parent after Match
React and Google's autocomplete Service and fetching zipcodes