the way to use setState with object

Advertisements
import React, {useState} from "react";



const SideListItem = () => {

    const [showItem, setShowItem] = useState([
        {id: "List A", clicked: true},
        {id: "List B", clicked: true},
        {id: "List C", clicked: true},
    ]);
    

    const clickList = () => {
        const value = showItem[0].clicked;
        setShowItem(() => {
            const boolValue = value? false: value === true;
            return boolValue;
        });

        

        return console.log(value);
                
    };

I want to make the next process below.

  1. when I click a button, the value of state is chaged.

    => if it is "true", then it changed in "false". And if "false", then "true".

But, my code didn’t work… When I used state with number, string, boolean, It worked.

Is there a way to use state with object?

Thank you in advance!

I tried this code.

const [clicked, setClicked] = useState(false);
const clickList = () => setClicked(!clicked);

But, I want to use state with object.

>Solution :

You can do it like this and add more statements if needed:

const clickList = () => {
    setShowItem(prevState => {
        return prevState.map(item => {
            if (item.id === "List A") {
                return {...item, clicked: !item.clicked};
            }
            return item;
        });
    });
};

But it’s better to get the id as param like this:

const clickList = (id) => {
    setShowItem(prevState => {
        return prevState.map(item => {
            if (item.id === id) {
                return {...item, clicked: !item.clicked};
            }
            return item;
        });
    });
};

Leave a Reply Cancel reply