Home > Blockchain >  How to update key value inside array when state changes?
How to update key value inside array when state changes?

Time:06-03

I am using React.js and in render method I have <Range/> component. What I want to do, is to be able to change the value and update the state's array accordingly. This is what I am talking about:

...
{
    this.state.tableData.map((i, k) => {
        return (
            <>
                <tr key={k}>
                    <td>
                        <div>
                            <Range
                                values={[i.s_rate]}
                                min={MIN}
                                max={MAX}
                                onChange={(values) => this.onSliderChangeS(values, k)}
    ...

So I trigger the onSliderChangeS function, which takes the new value of s_rate as values from the user, and it has to update and show my new this.state.tableData accordingly. I am trying to do it this way:

onSliderChangeS = (values, key) => {
    this.setState({
        valuesS: values,
        tableData[key].s_rate: parseInt(values)
    })
}

But this line this.state.tableData[key].s_rate: parseInt(values) doesn't seem to work at all. How can I do that?

CodePudding user response:

setState takes an object with key/value entries. this.state.tableData[key].s_rate itself is not a key name in your state. See if this helps:

onSliderChangeS = (values, key) => {
    const newTableData = [...this.state.tableData]
    newTableData[key].s_rate = parseInt(values)

    this.setState({
        valuesS: values,
        tableData: newTableData
    })
}

Also note the missing comma as pointed out by @FaFa

  • Related