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

Append dict key,value pairs into useState list

I am new to react and building a simple react app. And I am trying to insert or update current state with appending new dict's key value pairs into state.

App.js

function App() {
    const [valueList, setValueList] = useState([])

    const appendOnClick = (value, id) => {
        var newValue = {"value": value, "id": id}

        
        setValueList(value => [
          ...value,
          ...newValue
        ])

        console.log(valueList) // showing []

    }


    return (
        <>
            
                  <Form.Select aria-label="Default select example">
                    <option>Language</option>
                    <option value='1' onClick={() => appendOnClick("Good", 900)}>First Value</option>
                    <option value='2' onClick={() => appendOnClick("Better", 500)}>Second Value</option>
                  </Form.Select>

        </>
    )
}

I am trying to add these on click to the state like

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

[
    {
        value: "Good",
        id: 900,        
    },
    {
        value: "Better",
        id: 500,        
    },
]

I have tried many times but it is not setting the state.

I have tried using :-

    setValueList(value => ({
      ...value,
      ...newValue
  }))

But It showed newValue is not iterable.

Then I tried using

    setValueList(valueList=> [
      ...valueList,
      ...value
    ])

But it didn’t append either.

Any help would be much Appreciated. Thank You

>Solution :

when appending an object to the array, you don’t need to use the ... (spread operator)

setValueList(value => [
      ...value,
      newValue
])

also, console log won’t show you immediate value changes because useState is asynchronous. So use a useeffect for that

useEffect(() => {
        console.log(valueList)  

}, [valueList])
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