[Vuejs]-Data return from axios cant be written to variable

2πŸ‘

I believe the issue you are seeing has to do with the asynchronous nature of network calls. When axios submits the post request it returns a Promise then the addPost function continues executing. So the projectId gets logged after it the initial value gets set, but before the network request completes. Everything inside the then() function executes once the network request has been completed so you can test by moving the console.log to be executed once the request is done. You could also output the value in the template so you can see it update {{ projectId }}

        this.axios.post(uriProj, {
           projectName: this.post.project,
        }).then(response => {
            this.projectId = response.data.data
            console.log("project_id: "+this.projectId)
        });

I would ideally recommend using the VueJS dev tools browser extension because it allows you to inspect the state of your Vue components without having to use console.log or add random echos to your template markup.

0πŸ‘

@jfadich is correct. I recommend using async/await instead of then, it’s more intuitive to read.

async addPost(){
    //check if project exists else create
    let uriProj = 'http://localhost:4000/projects/add';
    let resp = await this.axios.post(uriProj, {
       projectName: this.post.project,
    })
    this.projectId = resp.data.data
    console.log("project_id: "+this.projectId)
}

Leave a comment