Search code examples
reactjsstate-managementreact-state-management

valid way to update a state property in react?


Very new to react so I wanted to check if this is correct. I don't get errors, but just to make sure I'm doing this in the right way.

state = {
        results: [],
    };

This method updates the state upon reach:

searchRequestHandler = () => {
        const filterCopy = this.state.filter;
        const dogsCharacteristicsData = dataFromServerModelerUponSearch(
            this.props.dogs
        );

        const resultsFromFilter = filterDataResults(
            filterCopy,
            dogsCharacteristicsData
        );

        this.setState({ formIsOpen: false, results: [...resultsFromFilter] });
    };

I'm also very curious to know how this could be done with restructuring. Thank you!

Here is what the data looks in the console for resultsFromFilter variable:

enter image description here


Solution

  • You are doing right while updating you result state. There are other ways you can update your result array like this:

    let result =  resultsFromFilter;
    this.setState({ formIsOpen: false, results: result});
    

    Or

    this.setState({ formIsOpen: false, results:  resultsFromFilter  });