简体   繁体   中英

Unable to set Vue.js data values inside axios response

I have created an axios request to my api for two routes. Using the response data I sort posts into the correct columns inside an array. This all works as it should but then when I come to assigning the value of this array to an array inside data() i get the following error;

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

So I figured maybe something was wrong with the array I was trying to assign. So I tried to assign boardPosts a simple string value and I still get the same error. Why can I not set the value of boardPosts inside my axios response?

my code;

    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 column index matches post column index value
                            if(columns[post.column_index]){
                                columns[post.column_index].posts.push(post);
                            }
                        });

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

That's because you're using not using an arrow function in axios.spread(...) . This means that you do not preserve the lexical this from the VueJS component, as function() {...} will create a new scope for itself. If you change it to use arrow function, then the this in the callback will refer to your VueJS component instance:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM