S
S
semki0962020-02-21 16:30:12
React
semki096, 2020-02-21 16:30:12

How to update data using setState?

A similar question already has an answer. He sounded like this - how to change the year.

getInitialState: function() {
  return {
    data: {
      'month' : 'January',
      'day' : '01',
      'year' : '2015'
  };
},

The answer was
this.setState({
    data: {
         ...this.state.data,
         year: '1980'
    }
})


My question is how to update the year only in the last object?
getInitialState: function() {
  return {
    data: [{
      'month' : 'January',
      'day' : '01',
      'year' : '2015'
      },
      'month' : 'January',
      'day' : '01',
      'year' : '2015'
      },
      'month' : 'January',
      'day' : '01',
      'year' : '2015'
      }
  ]
},

Answer the question

In order to leave comments, you need to log in

1 answer(s)
P
Petr Muhurov, 2020-02-21
@semki096

this.setState({
  data: [
    ...data.slice(0, data.length - 1),
    { ...data[data.length - 1], year: "2141" }
  ]
});

or more flexible
this.setState({
  data: data.map((item, index, source) =>
    index !== source.length - 1 ? item : { ...item, year: "2141" }
  )
});

or right
this.setState({
  data: data.reduceRight(
    (acc, item, index) => [
      ...acc,
      index !== 0 ? item : { ...item, year: "2141" }
    ],
    []
  )
});

maybe on the left
this.setState({
  data: data.reduce(
    (acc, item, index, { length }) => [
      ...acc,
      index !== length - 1 ? item : { ...item, year: "2141" }
    ],
    []
  )
});

but you can imagine
this.setState({
  data: Array.from(
    { length: data.length },
    (n => () => (
      n++, n !== data.length - 1 ? data[n] : { ...data[n], year: "2141" }
    ))(-1)
  )
});

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question