DEV Community

shrijan
shrijan

Posted on

State update issue

I have state object with properties as below

const initialState = {      
    active:false,
    section: []
}

const[state, setState] = useState(initialState)

const binType = ()  => {
    const selectedBin = []
    data.map((item) => {
      if(item.Bin == val){

        item.title = item.Item
        item.content = item.Description
        selectedBin.push(item)
       }

    })
    setState({..state,section:selectedBin})
    console.log(state.section)
}

Enter fullscreen mode Exit fullscreen mode

Outputs empty arrary. Any idea how to update object properties.

Top comments (4)

Collapse
 
shrijan profile image
shrijan

But if i do

const [section, setSection ] = useState([]);
const binType = ()  => {
    const selectedBin = []
    data.map((item) => {
      if(item.Bin == val){

        item.title = item.Item
        item.content = item.Description
        selectedBin.push(item)
       }

    })

   console.log(selectedBind) //outputs array
    setState({...section,selectedBin})
   console.log(section) //outputs array
}
Enter fullscreen mode Exit fullscreen mode

I am not sure if i am doing something wrong here

setState({...state,section:selectedBin})
Enter fullscreen mode Exit fullscreen mode

Thanks for your help

Collapse
 
arunavamodak profile image
Arunava Modak

Instead of trying to log it right after setState, you can try to write a useEffect, which watches for changes in state and print it there.

The problem here is, your state value is getting logged before the update in completed in your state.

Collapse
 
korzo profile image
korzo

Because you never update selectedBin variable.
Also state will be updated on next re-render.

Collapse
 
shrijan profile image
shrijan • Edited

Can you please clarify what do mean by selectedBin variable is never updated.

const initialState = {      
    active:false,
    section: []
}

const[state, setState] = useState(initialState)

const binType = ()  => {
    const selectedBin = []
    data.map((item) => {
      if(item.Bin == val){

        item.title = item.Item
        item.content = item.Description
        selectedBin.push(item)
       }

    })

   console.log(selectedBind) //outputs array
    setState({...state,section:selectedBin})

}
useEffect(() => {
        console.log('sections',state.section)
},[state.section])
Enter fullscreen mode Exit fullscreen mode

I have updated code still same issue. Array is empty.

Thanks for your help