Home > Back-end >  Append dict key,value pairs into useState list
Append dict key,value pairs into useState list

Time:12-16

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

[
    {
        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

CodePudding user response:

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])
  • Related