2

How can I dynamically set the name of the array in state, to get it from state.

onCheckBoxItemClickList(e, value, path) {
    console.log(e.target.checked)
    if (e.target.checked) {
        //append to array
        this.setState({
            [path]: this.state.[path].concat([value])
        })
    } else {
        //remove from array
        this.setState({
            [path]: this.state.[path].filter(function (val) {
                return val !== value
            })
        })
    }
}

I know how to dynamically set and get a key in state, but when I try and do

[path]: this.state.[path].concat([value])

I get the below error:

error Image

Any help would be greatly appreciated, Thanks

0

1 Answer 1

7

You have an extra dot in your code (after state):

[path]: this.state.[path].concat([value])

Should be:

[path]: this.state[path].concat([value])

Then whenever you want to set the state based on the previous state, you should use the setState which takes a callback in, with the prevState as argument.

So your code should look something like:

onCheckBoxItemClickList(e, value, path) {
    console.log(e.target.checked)
    if (e.target.checked) {
        //append to array
        this.setState(prevState => ({
            [path]: prevState[path].concat([value])
        }))
    } else {
        //remove from array
        this.setState(prevState => ({
            [path]: prevState[path].filter(function (val) {
                return val !== value
            })
        }))
    }
}
Sign up to request clarification or add additional context in comments.

1 Comment

Cheers thanks very much. It's a bit confusing that if you want to specify the array name/state key (not dynamically) it requires the dot beforehand, but doing it dynamically doesnt require the dot. This answer stackoverflow.com/a/43985409/2208342 on stack overflow made state a lot clearer to me and showed me that state is an object.

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.