Jordan
Jordan

Reputation: 123

Difference between .then and async/await in React

I need to PUT some data to backend, GET a response and use it to setState(), rendering the page syncronously. When using .then the changes made in editPost persist in about half of the time while using async/await seems to work fine(based on experimentation). I'm not sure why this happens since I've been told the two were equivalent:

.then:

onEditSubmit(e){
        e.preventDefault()
        const newPost = {
            id: this.state.id,
            title: this.state.titl,
            author: this.state.auth,
            content: this.state.cont
        }
        editPost(newPost)
        .then(axios.get('/blog')
        .then(response => {
            this.setState({
                posts: response.data,
                titl: '',
                auth: '',
                cont: ''
            })
        }))
    }

async/await:

async onEditSubmit(e){
    e.preventDefault()
    const newPost = {
        id: this.state.id,
        title: this.state.titl,
        author: this.state.auth,
        content: this.state.cont
    }
    await editPost(newPost)
    var response = await axios.get('/blog')
    await this.setState({
            posts: response.data,
            titl: '',
            auth: '',
            cont: ''
    })
}

editPost:

export const editPost = editPost => {
    return axios.put(`/blog/write/${editPost.id}`, {
        title :  editPost.title,
        author :  editPost.author,
        content :  editPost.content
    })
}

Note: I'm not sure if the fact that setState() being async has to do with this.

Upvotes: 0

Views: 307

Answers (1)

You should have a callback function in the first promise:

onEditSubmit(e){
    e.preventDefault()
    const newPost = {
        id: this.state.id,
        title: this.state.titl,
        author: this.state.auth,
        content: this.state.cont
    }

    editPost(newPost)
    .then(() => {
     axios.get('/blog')
    .then(response => {
        this.setState({
            posts: response.data,
            titl: '',
            auth: '',
            cont: ''
        })
    })
})
}

Upvotes: 1

Related Questions