user16137336
user16137336

Reputation:

Why react is not rendering updated states?

I am updating data even before initializing the state to that data, but react is rendering the old data.

class NewOrders extends Component {
    constructor(props) {
        super(props);
        this.state = {
            NewOrders:[],
        }
    }
    componentDidMount(){
        this.getNewOrders();
      }
      
    getNewOrders = async () => {
        let data = await api.get(`SellerOrdersAPI/${store.getState().auth.user.id}/`).then(({data})=>data);
        data.map(a =>
            this.get(a)
            )
        console.log(this.state.NewOrders) 
        this.setState({NewOrders:data}) 
    }
    get = async(a) => {
        let data1 = await itemApi.get(`/${a.item}/`).then(({data})=>data);
        let data2 = await userApi.get(`/${a.buyer}/`).then(({data})=>data);
        a.item = data1.title
        a.buyer = data2[0].first_name+' '+data2[0].last_name
    }
render() {
    return(
      -----
)}}

Now react is rendering the state displays old data but in console.log it's displaying updated data?

how to get this updated data at first?

image

Upvotes: 0

Views: 57

Answers (1)

trixn
trixn

Reputation: 16309

You are mutating the state directly by setting some properties on objects that are in your state in get(). React state should never be mutated:

// this mutates a which is an object already in your state
a.item = data1.title

As get() is async this will happen after you've already set data in getNewOrders(). React is not aware of those updates. You need to call this.setState again whenever you change anything inside of the state object. Also you should always create new objects instead of mutating objects in the state object.

Upvotes: 1

Related Questions