Ekin Alcar
Ekin Alcar

Reputation: 135

spread prevState with variable

I am trying to refactor a codebase and I got stuck somewhere. I am basically trying to update the state based on the onChange event of a select box.

In this case, my searchCriteria parameter in my handleFilterChange functions is ingredients.

But let's assume I have another select box that contains the options of anotherIngredients. I couldn't spread the prevState based on a variable.

I had to type ...prevState.ingredients

Is there a proper way to do that?

So my component state is:

 state = {
    ingredients: {
      name: "",
      operation: "",
      value: ""
    },
  anotherIngredients: {
      name: "",
      operation: "",
      value: ""
    }
  };

My handler is:

handleFilterChange = (event, searchCriteria, searchCriteriaKey) => {
    let newValue = event.target.value;
    this.setState(prevState => ({
      [searchCriteria]: {
        ...prevState.ingredients,
        [searchCriteriaKey]: newValue
      }
    }));
  };

My Select box component is :

<Select
  value={ingredients.name}
  options={[
            { key: "", value: "Please choose an ingredient" },
            { key: "ingredient1", value: "INGREDIENT 1" },
            { key: "ingredient2", value: "INGREDIENT 2" },
            { key: "ingredient3", value: "INGREDIENT 3" },
            { key: "ingredient4", value: "INGREDIENT 4" }
           ]}
           changeHandler={event =>
            this.handleFilterChange(event, "ingredients", "name")
           }
 />

Hope I could explain myself. Thank you!

Upvotes: 0

Views: 38

Answers (1)

FMCorz
FMCorz

Reputation: 2706

You should reuse your variable searchCriteria to extract the previous values from the state.

handleFilterChange = (event, searchCriteria, searchCriteriaKey) => {
    let newValue = event.target.value;
    this.setState(prevState => ({
        [searchCriteria]: {
            ...prevState[searchCriteria],
            [searchCriteriaKey]: newValue
        }
    }));
};

Upvotes: 1

Related Questions