Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to update key value inside array when state changes?

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?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading