Charanrajh Pepakayala
Charanrajh Pepakayala

Reputation: 67

Unable to update the array in the current state

This is my code. But when I'm trying to print the array, It's printing the empty array.

class FlatListItem extends Component{
    constructor(props){
        super(props)
        this.state={
            markers:[],
        }
    }

    changeSelectStatus=(key)=>{
        this.setState(prevState => ({
            markers: [...prevState.markers, key]
        }))
        console.log(this.state.markers)
    }
}

I want to push all the keys into markers array get it printed in the console (remote debugger).

Upvotes: 0

Views: 72

Answers (3)

Dhaval Patel
Dhaval Patel

Reputation: 7601

you can use the await while setting the state like

fillArray = async () => {
    await this.setState(prevState => ({
        marker: [...prevState.marker, { id: 1, name: 'change' }],
    }));
    console.log(JSON.stringify(this.state.marker));
};

please check the Demo here

Upvotes: 0

Billy Koswara
Billy Koswara

Reputation: 497

Your console log is generated before the state change to see if your code work maybe you should change your console log location

Example

this.setState(prevState => ({
    markers: [...prevState.markers, key]
}), () => console.log(this.state.markers))

If the state not change after applying the code

Maybe you could try this

changeSelectStatus(key) {
        let x = this.state.markers
        x.push(key)
        this.setState({ markers = x }, () => console.log(this.state.markers))
}

Upvotes: 0

Varun Suresh Kumar
Varun Suresh Kumar

Reputation: 879

setState is an async function, if you wanna see the state changes you can pass a callback to see the state changes

class FlatListItem extends Component{
    constructor(props){
        super(props)
        this.state={
            markers:[],
        }
    }

    changeSelectStatus=(key)=>{
        this.setState(prevState => ({
            markers: [...prevState.markers, key]
        }), () => console.log(this.state.markers) )

    }
}

Upvotes: 1

Related Questions