Vue 3 – ‘this’ is unreachable / ‘this’ targets the wrong section

  javascript, this, vuejs3

In Vue 3, I’m trying to target a property in the data() function from within a nested function in the mounted() hook. Here’s my code example:

export default defineComponent({
    components: {
        ProgressTable
    },
    name: 'Sidebar',
    emits: ['remove-sidebar'],
    data () {
        return {
            userData: authStore.state,
            trackedSymptoms: []
        };
    },
    props: {

    },
    mounted () {
        const url = '...';
        const action = 'Progress-Tracking';
        const dispensaryId = this.userData.userData.dispensaryId;
        const customerId = this.userData.userData.customerId;
        const token = localStorage.getItem('jwt');

        const params = {
            action: action,
            dispensaryId: dispensaryId,
            customerId: customerId,
            token: token
        };

        axios({
            method: 'get',
            url: url,
            params: params,
            headers: {
                'Content-Type': 'application/x-www-form-urlencoded'
            }
        })
            .then(function (response) {
                this.trackedSymptoms = response.data.symptomTracking;
                console.log(response);
            })
            .catch(function (error) {
                console.log(error);
            });
    }
});

In the Axios code, this line:

this.trackedSymptoms = response.data.symptomTracking;

How can I target the trackedSymptoms: [] instead of targeting the function that the above line is located in?

Source: Ask Javascript Questions

LEAVE A COMMENT