Two setState functions in one onclick

Viewed 513

I'm trying to call two functions in a single onclick, however only the first one sets the state. Following solutions from other answers, I tried calling a single function which would then call the Add() and Del() functions, but that didn't work.

This is my code:



    const [obj, setObj] = useState(['door1','mc','start'])
    
    const Add = (a) => {
        var newObj = [...obj]
        a.map((i) => newObj.push(i))
        console.log(newObj)
        setObj(newObj)
        console.log(obj)
    }

    const Del = (d) => {
        const newObj = obj.filter((o) => o!=d)
        console.log(newObj)
        setObj(newObj)
    }


    return (
        <div class="main">
            {obj.includes('start') && <button className="btn1" onClick={() => {Add(['text1']);Del('start')}} >Start</button>}
            {obj.includes('text1') && <div className="text text1" onClick={() => {Del('text1');Add(['text2'])}}>I've been trapped here for hours</div>}
        </div>
    )

In specific, this part:

{obj.includes('start') && <button className="btn1" onClick={() => {Add(['text1']);Del('start')}} >Start</button>}

How can I set state twice in one onclick?

1 Answers

You can create a handleClick function before the return statement, and add this function to your button's onClick, like this:

const handleClick = () => {
    Add(["text1"])
    Del("start")
}

<button className="btn1" onClick={handleClick}>
    Start
</button>
Related