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

the way to use setState with object

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".

    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

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;
        });
    });
};
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