Maikon Weber Carvalho
Maikon Weber Carvalho

Reputation: 45

Set State Hooks with array and objetcs

***Basically I want to put this state, but I don't know what the initial state will be because when I use setState it doesn't change my

state. The state I want to set will be an array with two objects and inside them there are two properties that received another array


   let GraphFilteEvent = queryEventTimelineFilteredAPI(eventdate).then(ret => {
                const current = []
                const date = []
                const date2 = []
                const past = []
                if (ret === undefined) { } else {
                    
                    const diff = (eventdate.to - eventdate.from)
                    const diffrt  = timeConversion(diff)
                    const diff_string = diffrt.slice(0, 1)
                    const raw = JSON.parse(ret)
                   
    
                    raw.slice(0, diff_string).forEach((elem, i ) => {
                        current.unshift({ x: elem.day, y: elem.sum })
                        date.unshift({ z: elem.date })
                        
    
                    })
    
                    raw.slice(diff_string).forEach((elem, i ) => {
                        past.unshift({ x: elem.day, y: elem.sum })
                        
                        date2.unshift({ z: elem.date}
    
                    })

             }) 
 
            const retvalor = [{data: current, date: date },{data: past , date: date2}]
            setGraphState(retvalor)
            console.log(retvalor)
            
            console.log(graphState)

       
    promiseArray.push(GraphFilteEvent)

            Promise.all(promiseArray).then(value => {

                setLoading(true)
            })
        }
        

}

This is full code with promisse.

Some erros in the scope were my copy and past for the stackover flow attetion on the set state with promisse

Upvotes: 0

Views: 66

Answers (2)

Fathma Siddique
Fathma Siddique

Reputation: 264

You can try this way.

const [graphState, setGraphState] = useState([{ data: current, date: date 
},{data: past , date: date2}])


const retvalor = [{data: current, date: date },{data: past , date: date2}]

setGraphState(prev=> retvalor ) 

Upvotes: 1

vicky k
vicky k

Reputation: 27

you have to set the state inside some onclick or onchange function or inside promis

Upvotes: 0

Related Questions