0

I am creating arrays of objects and storing it on variables like this:

const nameOption = nameOptions(listHotels);
const estadoOption = stateOptions(listHotels);
const cityOption = cityOptions(listHotels);

my state is currently like this:

selectFilter: [
      { id: 1, type: 'Name'},
      { id: 1, type: 'Estado'},
      { id: 1, type: 'Cidade'},
    ],

I want to add these variables in a property called "options", like so:

selectFilter: [
          { id: 1, type: 'Name', options: nameOption},
          { id: 1, type: 'Estado', options: estadoOption},
          { id: 1, type: 'Cidade', options: cityOption},
        ],

how do I do it using the immutable react way?

1
  • You have to create a new array and replace the old one Commented Dec 19, 2018 at 17:59

3 Answers 3

2

First store the values to be inserted into a plain object, where the properties match the type values of selectFilter :

const options = {
    Name: nameOptions(listHotels),
    Estado: stateOptions(listHotels),
    Cidade: cityOptions(listHotels)
}

Then merge that with selectFilter into the extended version of it:

this.setState(prevState => ({
    selectFilter: prevState.selectFilter.map(filter => 
        ({...filter, options: options[filter.type]})
    )
}));

NB: there is probably a more efficient way to build the options object, since you seem to iterate listHotels for each property. This could probably be done in one sweep using reduce. But without details about what these functions (nameOptions, stateOptions, ...) do there is not much I can offer for that. Look into calling listHotels.reduce.

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

Comments

1

You can use Object.assign() to duplicate your state into an new object. This object is now mutable. Once done modifying it, you then replace your entire state with the new version. Here is an example of how that could be done.

  handleChange= () => {
    let mutableState = Object.assign({}, this.state);
    mutableState.thingToChange = foo;
    this.setState(mutableState);
  };

Comments

-2
this.setState(({selectFilter}) => (
    [
         {...selectFilter[0], options: nameOptions},
         {...selectFilter[1], options: estadoOptions},
         {...selectFilter[2], options: cityOptions},
    ]
);

1 Comment

You should really put an explanation here.

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.