Invalid attempt to spread non-iterable instance with django REST and Vue.js
Answer a question
I have an API endpoint made from Django Rest Framework and I use Vue.js to display it in front-end.
I use a api.service.js
to fetch the data:
import { CSRF_TOKEN } from "./csrf_token.js"
function handleResponse(response) {
if (response.status === 204) {
return '';
} else if (response.status === 404) {
return null;
} else {
return response.json();
}
}
function apiService(endpoint, method, data) {
const config = {
method: method || "GET",
body: data !== undefined ? JSON.stringify(data) : null,
headers: {
'content-type': 'application/json',
'X-CSRFTOKEN': CSRF_TOKEN
}
};
return fetch(endpoint, config)
.then(handleResponse)
.catch(error => console.log(error))
}
export { apiService };
So far there is my Home.vue
where I want to display the data from my API (restaurants reviews):
<template>
<div class="home">
<div class="container">
</div>
</div>
</template>
<script>
import { apiService } from "@/common/api.service.js"
export default {
name: "home",
data () {
return {
reviews: []
}
},
methods: {
getReviews() {
let endpoint = "/api/restaurant_review/";
apiService(endpoint)
.then(data => {
this.reviews.push(...data.results)
})
}
},
created() {
this.getReviews()
console.log(this.reviews)
}
};
</script>
I know my API works fine because I checked it with Django Browsable API:
So I did a console.log()
with the data was correctly fetched but I get this error:
Uncaught (in promise) TypeError: Invalid attempt to spread non-iterable instance. In order to be iterable, non-array objects must have a Symbol.iterator method.
So basically I can't spread my API array into reviews
, that is also an array, how can I fix it?
When I do a console.log(data):
Answers
It looks like the data
returned from the API doesn't have a property called results
which is undefined when you try to spread it (only arrays and object support that spread operator), so you should do :
this.reviews.push(...data)
更多推荐
所有评论(0)