简体   繁体   中英

Why new value of state is not rendered in react Js after mutation

I am working on React Js in class component I am declaring some states and then getting data from API and changing that state to new value but React is not rendering that new value of state. but if I console.log() that state it gives me new value on console.

if I visit another page and then return to this page then it is rendering new value of state (3).

My code

class Home extends Component {
    constructor(props) {
        super(props);
        this.state = {
            unread:0,
        }
        this.getUnread()   
    } 
getUnread = async() => {
        let data = await Chatapi.get(`count/${this.props.auth.user.id}/`).then(({data})=>data);
        this.setState({unread:data.count});
        console.log(this.state.unread)
    }
render() {
        const { auth } = this.props;
    return(
    <div>
    {this.state.unread}
    </div>
)}

This is printing 3 on console but rendering 0 on screen. How can I get updated state(3) to render on screen.

async/await and Promise.then() are two different approaches for handling asynchronous operations. So you should decide and use one of them, not both of them together. You can use one of the following:

getUnread = async() => {
  const data = await Chatapi.get(`count/${this.props.auth.user.id}/`)
  this.setState({ unread:data.count });
  console.log(this.state.unread)
}
getUnread = async() => {
  Chatapi.get(`count/${this.props.auth.user.id}/`).then(data => this.setState({ unread:data.count }) )
  console.log(this.state.unread)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM