0

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?

2 Answers 2

1

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

Sign up to request clarification or add additional context in comments.

1 Comment

so how would I update the two values in the hierarchyTableFilters object with their corresponding values in the previouslySelectedFilter object I'm getting from the redux store? The two values technically do not have any existing state on them because I'm setting them as the page has just finished loading
1

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);
}

1 Comment

That's actually the direction I started going in once I started running into complications with my original way. Thanks for the insight!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.