Reputation: 3885
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 };
}
Upvotes: 4
Views: 13226
Reputation: 282030
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(nextProps) {
console.log(nextProps.currentPage)
}
Upvotes: 5
Reputation: 387
I just ran into this also. It is an asynchronous issue when updating props like everyone is saying. I solved it by using async await. If you want to get the updated props immediately then you can do something like:
async function myFunction () {
await this.props.actions.setCurrentPage(tempPage);
console.log(this.props.currentPage); // shows updated props
}
In this code the console log waits for the async operation to complete then gets your props.
Upvotes: 2
Reputation: 15924
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.
Upvotes: 2