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

When i clicking second time on OnClick( SetState) i got a mistake, what should i do?

When i clicking on <a onClick{() => "function"}> first time it works everything changing fine, but when i clicking second time everything breaks.
here i got code :

function ref(sub) {
    console.log(Subjects)
    SetSubjects(Subjects[sub] = true)
    console.log(Subjects)
};

const [Subjects, SetSubjects] = useState({
    "Mathematics": false,
    "Physics": false,
    "Ukranian": false,
    "English": false,
    "Chemistry": false,
    "Informatics": false,
    "History": false
})
return (
        <div className="area">
            <div className="logo_header"><a className="logo_header_text" href="/">Owly</a></div>
            <h1 className="tittle">Choose the Subject</h1>
            <div className="select_btns">
                <a onClick={() => ref("Mathematics")} >Mathematics</a>
                <a onClick={() => ref("Physics")} >Physics</a>
                <a onClick={() => ref("Ukranian")} >Ukranian</a>
                <a onClick={() => ref("English")} >English</a>
                <a onClick={() => ref("Chemistry")}>Chemistry</a>
                <a onClick={() => ref("Informatics")}>Informatics</a>
                <a onClick={() => ref("History")}>History</a>
            </div>

here i got screens
First click:
first click

Second click:
enter image description here

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

and it doesn’t matter which button i choose

>Solution :

This isn’t doing what you think:

SetSubjects(Subjects[sub] = true)

The result of the expression Subjects[sub] = true is the value true, so you’re setting Subjects to the value true. Which of course doesn’t have any of the properties you’re expecting from your Subjects object.

I suspect you’re looking for this:

SetSubjects({ ...Subjects, [sub]: true })

This will set Subjects to an object containing all of the properties currently on Subjects, as well as set the property defined by the value in sub to be true.

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