Bobby Tables
Bobby Tables

Reputation: 163

values overwriting each other in object in setState reactjs

I am trying to pre-populate filter values that I have saved in the redux store when a user navigates back to that page where they set the filters. However, when I am going to set the state, I'm having trouble with the last set value overwriting the existing one. This is how I set the state in the constructor:

this.state = {
  hierarchyTableFilters: {
    hierarchy: null,
    signOffStatus: null,
  },
};

and then this is how I'm going to set the state in the called function with the stored data from redux:

const {userState} = this.props.userInfo;
const previouslySelectedFilter = userState.state.hierarchyTableFilters;

if (previouslySelectedFilter) {
  this.setState({
    hierarchyTableFilters: {
      hierarchy: previouslySelectedFilter.hierarchy,
      signOffStatus: previouslySelectedFilter.signOffStatus,
    },
  });

Whatever state gets set last is the only filter that appears pre-filtered. Is there a way to set state for two different values in an object or do I have to go about this in a different way?

Upvotes: 0

Views: 278

Answers (2)

willwoo
willwoo

Reputation: 560

could you flatten your data structure to take advantage of the setState merging functionality?

this.state = {
   filtersHierarchy: null
   filtersSignOffStatus: null
 };

with the latter piece being:

if (previouslySelectedFilter) {
  const { hierarchy, signOffStatus } = previouslySelectedFilter;
  let newState = {};
  if (hierarchy) newState.filtersHierarchy = hierarchy;
  if (signOffStatus) newState.filtersSignOffStatus = signOffStatus;
  this.setState(newState);
}

Upvotes: 1

Danny Delott
Danny Delott

Reputation: 6998

If you need to set local state based on previous local state, you should use the setState callback pattern instead.

this.setState(previousState => ({ ... }))

This is because setState does batch updates. See the docs on setState

Upvotes: 1

Related Questions