Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 };
}
like image 965
user1189352 Avatar asked Oct 14 '25 08:10

user1189352


1 Answers

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)
}
like image 104
Shubham Khatri Avatar answered Oct 17 '25 01:10

Shubham Khatri