Mohamed Gabr
Mohamed Gabr

Reputation: 716

receiving a json response with vue.js2 in laravel

sending a request and getting response which bases on it i want to chege the status and display something different, can't figure out what's the problem, the route seems to be working fine and I'm receiving a response which looks like this enter image description here

I'm trying to access this using Vue component and I'm getting that error status is not defined, here is my Vue component

<script>
    export default {
        mounted() {
                axios.get('/userfound/' + this.profile_user_id)
                .then(function (response) {
                    console.log(response);
                    this.status = response.data.status;                   
                })
                .catch(function (error) {
                    console.log(error);
                  });
                },
        props: ['profile_user_id'],
        data(){
            return {
                status: ''
            }        
        },
        methods:{
            add_friend(){
                // this.loading = false
                axios.get('/add_friend/' + this.profile_user_id)
                .then(function (response) {
                    console.log(response);
                    if (response.data == 1) {
                        this.status = 'waiting'
                    }

                })
                .catch(function (error) {
                    console.log(error);
                  });
                }
            }
        }
</script>

why am i getting this error: TypeError: cannot read property 'status' of undefined .. i've tried "this.status = response.body.status" and "this.status = response.data.status" but neither is working

Upvotes: 1

Views: 1437

Answers (1)

Pradeepb
Pradeepb

Reputation: 2572

I believe there is an issue with the scope of a variable. Try below answer:

<script>
export default {
    mounted() {
            var self = this;
            axios.get('/userfound/' + self.profile_user_id)
            .then(function (response) {
                console.log(response);
                self.status = response.data.status;                   
            })
            .catch(function (error) {
                console.log(error);
              });
            },
    props: ['profile_user_id'],
    data(){
        return {
            status: ''
        }        
    },
    methods:{
        add_friend(){
            // you can do same here as well
            var self = this;
            axios.get('/add_friend/' + self.profile_user_id)
            .then(function (response) {
                console.log(response);
                if (response.data == 1) {
                    self.status = 'waiting'
                }
            })
            .catch(function (error) {
                console.log(error);
              });
            }
        }
    }
</script>

Upvotes: 3

Related Questions