Encountering difficulties in updating Vue.js data values after receiving response from axios

I've set up an axios request to my API for two different routes. Upon receiving the response data, I organize the posts into the appropriate columns within an array successfully. However, when attempting to assign the value of this array to another array inside data(), I encounter the following error;

TypeError: Cannot set property 'boardPosts' of null
    at eval (SummaryBoard.vue?2681:90)
    at wrap (spread.js?0df6:25)

I thought that maybe there was an issue with the array I was trying to assign. To test this assumption, I tried assigning a simple string value to boardPosts and still received the same error. Why am I unable to set the value of boardPosts within my axios response?

Here is the code snippet in question;


import axios from 'axios';

export default {
    name: 'SummaryBoard',
    data() {
        return {
            boardPosts: '',
        }     
    },
    created() {
        this.getBoardData();
    },
    methods: {
        getBoardData() {
            function getBoardColumns() {
                return axios.get('http://localhost:5000/api/summary-board/columns');
            }

            function getBoardPosts() {
                return axios.get('http://localhost:5000/api/summary-board/posts');
            }

            axios.all([getBoardColumns(), getBoardPosts()])
                .then(axios.spread(function(columnData, postData) {
                    let posts = postData.data;
                    // add posts array to each object
                    let columns = columnData.data.map(obj => ({...obj, posts: []}));

                    posts.forEach((post) => {
                        if(columns[post.column_index]){
                            columns[post.column_index].posts.push(post);
                        }
                    });

                    console.log(columns);
                    this.boardPosts = 'hello';
                }))
                .catch(error => console.log(error));
        }
    }
}

Answer №1

The reason for this issue is that you are not using an arrow function in axios.spread(...). By not using an arrow function, the lexical scope of this from the VueJS component is not preserved because a regular function function() {...} creates its own scope. To resolve this, switch to using an arrow function so that the this in the callback will correctly reference your VueJS component instance:

axios.all([getBoardColumns(), getBoardPosts()])
    .then(axios.spread((columnData, postData) => {
        // Add your logic here
    }))
    .catch(error => console.log(error));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Trouble fetching values from Google Sheets using getBatch method in JavaScript

Using javascript fetch() to retrieve a single value from a Google sheet works perfectly fine for me. However, when attempting to read multiple ranges, I encounter a 403 error. The following code executes without any issues: const apiKey = 'insert-you ...

Is it possible for a d3 chart to render twice in one area if it's rendered in two different places?

When attempting to showcase two distinct d3 pie charts on my webpage within individual mat-cards, they both end up displaying in the svg tag of the first d3 chart in my code. This is what my code looks like: <section class="three"> <! ...

Is it time for a countdown clock?

Looking to create a Countdown timer? Upon page load, the clock initiates a countdown. Once it reaches zero, it will automatically redirect the browser to a new page. Came across this resource, however, it did not fulfill my needs: ...

How to Transfer a jQuery Variable to a PHP script within a Modal using AJAX

I am currently facing an issue with retrieving the value of a variable and displaying it in a modal that is supposed to open. I have attempted to use the POST method but so far, no changes have occurred. Both sets of code are located within index.php. Her ...

Tips for connecting a Django API project with a nodejs and react frontend

I'm currently working on a Django API project and I am considering incorporating Node.js into the mix. Additionally, I am interested in using React for the frontend of the application. Is this combination of technologies feasible? Would it be advisabl ...

Sending a POST request using Node.js XHR

I am currently utilizing nodejs to send a POST command to a server. In this process, I am also making use of the node-xmlHttpRequest module created by driverdan. However, I am encountering a problem related to the content-type setting, which is resulting i ...

Testing a Vue component with Jest: A step-by-step guide

I have a Vue component and I want to run its methods from my unit test file: @Component export default class Breadcrumb extends Vue { breadcrumbList: BreadcrumbData[] = []; mounted(): void { this.breadcrumbList = (this.$route.meta .breadcru ...

Expanding upon the initial instance, the parent div effortlessly widens without any visual effects as the child element is revealed or concealed

Experiencing an issue where the div element opens and closes smoothly with jQuery animation, but its parent does not. As a result, the entire page content appears jerky. Here is a demo: http://jsfiddle.net/neDZP/7/ HTML: <div id="A_to_Z_top"> ...

The directives for ion-slide-page within ion-slides are experiencing rendering issues

Currently, I am working on an Ionic App (using an Ionic 1 codebase) and trying to incorporate the ion-slides/ion-slide-page directives into a page. However, I am facing difficulty in getting each individual ion-slide-page directive to sit horizontally next ...

Monitor the item for fluctuations in its worth

Is there a way to watch an object and wait for all of its values to become truthy? const myObject = { key1: null, key2: null, key3: null, } // Perform asynchronous operations that update myObject const checkValues = async () => { awa ...

Why isn't my JavaScript Alert displaying a string message?

I'm feeling a bit puzzled and I have a feeling there must be an easy solution, so please lend me a hand. Here's the code snippet that is causing me some confusion: $new = "1"; <script language="javascript"> alert(<?php echo $new; ...

Tips on efficiently modifying data in a JSON file with the help of jQuery and AJAX

My goal is to modify the JSON data by changing the value of the "secret" key when the uid is equal to 0090000219. Here is the initial JSON: [ { "id":23, "uid":"0090000219", "cid":"0090000013", "extension":"201", "secret":"Myojyo42_f", "leader":true, "sim ...

Currency Conversion Rates Showcased

Why does the exchange rate consistently show as N/A in the code below after selecting a currency pair, and how can this issue be resolved effectively? I anticipate that the exchange rate value will be displayed accurately once a pair is selected. What st ...

Refreshing browser data with JQuery ajax when the browser is refreshed

Is there a way in JavaScript or jQuery to stop the page from refreshing (F5) and only update certain parts of the page using Ajax? I attempted the following code, but it did not work: $(window).bind('beforeunload', function(event) { ...

Insert a datum into an existing element

I need to modify a link by removing the title attribute and instead placing the title text in a data attribute called data-title. I want to achieve this using jquery. Can someone please provide guidance on how to do this? The goal is to remove the title e ...

The <br> tag does not appear to be displaying correctly on the AngularJS page

I've encountered an issue in my angularJS application where setting a String value with the " " tag does not render as HTML and instead prints as "AA<br>BB" on the page. Even replacing it with "&lt;br&gt;" doesn't render properly, ...

It's likely that the data source is incorrect for the 'GET_LIST' operation

Trying to utilize react-admin with a Hasura adapter. Encounter an error when attempting to use the cruds. The response to 'GET_LIST' must follow this format { data: ... }, however, the received response is missing a 'data' key. Authen ...

Creating an array that contains multiple elements from an object stored in local storage is a simple process

Looking to create an array that contains all the product IDs stored in the local storage object of my online shopping cart. However, the current function I have generates separate arrays for each product ID instead of consolidating them into one single arr ...

Why am I receiving undefined for req.user in passportjs?

After setting up passportJS with my node express app, I encountered an issue where the req.user is undefined when making a login/register request. I am not sure what went wrong or if I missed something in the configuration of passport js. In my setup, I us ...

What are the steps to transform a blob into an xlsx or csv file?

An interesting feature of the application is the ability to download files in various formats such as xlsx, csv, and dat. To implement this, I have utilized a library called fileSaver.js. While everything works smoothly for the dat/csv format, there seems ...