Syntax Error: Unexpected reserved word 'await' [closed] - vue.js

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 1 year ago.
Improve this question
I'm using nuxt.js and I'm getting this error
Syntax Error: Unexpected reserved word 'await'
this is the code
<template>
<div class="mt-6">loggedInUser: {{ loggedInUser }}</div>
</template>
<script>
export default {
middleware: 'auth',
async fetch() {
await this.$auth
.fetchUser()
.then((response) => (this.loggedInUser = response.data.data))
},
data() {
return {
loggedInUser: this.$auth.user.data,
}
},
}
</script>
<style>
</style>

you are exporting an object. an object has key value pairs.
You have not defined key for async fetch() and for data
consider doing it like this.
export default {
middleware: 'auth',
fetch: async () => {
await this.$auth
.fetchUser()
.then((response) => (this.loggedInUser = response.data.data))
},
data: () => {
return {
loggedInUser: this.$auth.user.data,
}
},
}

Related

Creating an API pull for Vue.js [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 9 months ago.
Improve this question
I have no idea what I am getting wrong or why this is not working, I am just trying to get the photos of random dogs api to work and it is not working. See code below.
export default {
data() {
return {
posts: [],
};
},
methods: {
async getData() {
try {
let response = await fetch ("https://dog.ceo/api/breeds/image/random");
this.posts = await response.json();
} catch (error){
console.log(error)
}
}
}
};
You have to call your getData function. One possible solution is, you can call your getData function in mounted lifecycle hook. Here is a vue playground link
<script >
export default {
data() {
return {
posts: [],
};
},
mounted(){
this.getData();
},
methods: {
async getData() {
try {
let response = await fetch ("https://dog.ceo/api/breeds/image/random");
this.posts = await response.json();
} catch (error){
console.log(error)
}
}
}
};
</script>
<template>
<img :src="posts.message" alt="img">
</template>

AsyncData with multiple requests in Nuxt

I'm trying to get the answer from two API routes and depending on the result display the data. But for some reason, when I trying to use more than 1 axios call it doesn't work, failing with 404/500 error.
I've tried following:
<template>
<div v-if="blogPost">
<p>post</p>
</div>
<div v-else-if="blogCategoryPosts">
<p>category,posts</p>
</div>
</template>
<script>
export default {
async asyncData({ $axios, app, route }) {
const blogPost = await $axios.get(`${process.env.API_DOMAIN}/api/blog/posts${route.path}`)
const blogCategoryPosts = await $axios.get(`${process.env.API_DOMAIN}/api/blog/categories${route.path}`)
return {
blogPost: blogPost.data,
blogCategoryPosts: blogCategoryPosts.data,
}
},
}
</script>
and
<script>
export default {
async asyncData({ $axios, app, route}) {
const [blogPost, blogCategoryPosts] = await Promise.all([
$axios.get(`${process.env.API_DOMAIN}/api/blog/posts${route.path}`),
$axios.get(`${process.env.API_DOMAIN}/api/blog/categories${route.path}`),
])
return {
blogPost: blogPost.data,
blogCategoryPosts: blogCategoryPosts.data,
}
},
}
</script>
Each call works fine separately but together they don't. Any idea why is that?
You should await your Promise.all like this
const [blogPost, blogCategoryPosts] = await Promise.all([
$axios.get(`${process.env.API_DOMAIN}/api/blog/posts${route.path}`),
$axios.get(`${process.env.API_DOMAIN}/api/blog/categories${route.path}`),
])
Also, don't forget the , at the end of the first $axios.
I gave a similar answer here few time ago.
PS: if you want to have those issues fixed quickly, use ESlint.
If you want a tutorial on how to have both ESlint and Prettier, you can follow my tutorial here.
So in my case it was sufficient to point on .then and .catch for axios
export default {
async asyncData({ $axios, app, route}) {
const blogPost = await $axios.get(`${process.env.API_DOMAIN}/api/blog/posts${route.path}`).then(response => response.data).catch(error => {})
const blogCategoryPosts = await $axios.get(`${process.env.API_DOMAIN}/api/blog/categories${route.path}`).then(response => response.data).catch(error => {})
return {
blogPost: blogPost,
blogCategoryPosts: blogCategoryPosts,
}
},
}
Everything worked well. Also I sort of misunderstood 500 error, i thought it a generic message, but my API was just telling me that category not found.

Vue can't read property movies of undefined

So basically i want to input a keyword after that i will send an api request and after I receive the results I will push it to my movies(object) then loop through the results.
This is my code
<script>
import MovieCard from '~/components/MovieCard.vue'
import _ from 'lodash';
import axios from 'axios';
export default {
name: 'Navbar',
components:{
MovieCard
},
data () {
return {
search: false,
input: '',
movies: {},
}
},
methods:{
searchMovies: _.debounce((e) => {
axios.get('https://api.themoviedb.org/3/search/movie?api_key=123456789&query='+e.target.value)
.then(response => {
this.movies.push(response.data.results);
})
}, 2000)
}
}
</script>
And this is from my form input
<input #keyup="searchMovies" v-model="input" type="text" class="w-full sm:h-20 h-16 dark2 border-0 md:pl-8 pl-4 md:pr-64 pr-24 focus:outline-none text-white inline-block">
This is the error
error
And this is the results of my API request
Api results
It means that it is unable to find this. You should rewrite your function like so:
searchMovies() {
_.debounce((e) => {
axios
.get(
"https://api.themoviedb.org/3/search/movie?api_key=123456789&query=" +
e.target.value
)
.then((response) => {
this.movies.push(response.data.results);
});
}, 2000);
}
And by the way, this.movies is an object so you cannot use push.
You need to change your debounce callback to a function because an arrow function wouldn't bind this to the vue instance. In vuejs doc that writes:
Don’t use arrow functions on an options property or callback, such as
created: () => console.log(this.a) or vm.$watch('a', newValue =>
this.myMethod()). Since an arrow function doesn’t have a this, this
will be treated as any other variable and lexically looked up through
parent scopes until found, often resulting in errors such as Uncaught
TypeError: Cannot read property of undefined or Uncaught TypeError:
this.myMethod is not a function.
data () {
return {
search: false,
input: '',
movies: [],
}
},
methods:{
searchMovies: _.debounce(function(e) {
axios.get('https://api.themoviedb.org/3/search/movie?api_key=123456789&query='+e.target.value)
.then(response => {
this.movies.push(response.data.results);
})
}, 2000) }

Calling API in method and getting [object Promise]

I'm using Nuxt.js in static site mode, and trying to get an image from an API using a string passed in a prop, however, in the template I am getting [object Promise]. I would've thought that return before the get request would resolve the promise, but I think my grasp of promises and Nuxt.js a little off. Any help would be greatly appreciated.
<template>
<div>
{{ getThumbnailSrc() }}
</div>
</template>
<script>
import axios from 'axios'
export default {
props: {
link: {
type: String,
required: true
}
},
data() {
return {
imageUrl: null
}
},
methods: {
getVimeoId(link) {
return link.split('/').pop()
},
getThumbnailSrc() {
return axios
.get(
`https://vimeo.com/api/v2/video/${this.getVimeoId(
this.link
)}.json`
)
.then(response => {
const vimeoThumbnailUrl = response.data[0].thumbnail_large
console.log(vimeoThumbnailUrl)
return {
vimeoThumbnailUrl
}
})
.catch(error => {
console.log(error)
})
}
}
}
</script>
It sure won't! XHR requests are asynchronous and therefore the template has no idea that it needs to wait.
Solve it by using an additional data property on the component, and using that instead:
data() {
return {
imageUrl: null,
thumbnailSrc: null
}
},
And in your callback:
.then(response => {
const vimeoThumbnailUrl = response.data[0].thumbnail_large
console.log(vimeoThumbnailUrl)
this.thumbnailSrc = vimeoThumbnailUrl
})
Now you can use {{thumbnailSrc}} and it will load appropriately.

How to use Axios with Vue-Multiselect?

New to using Vue-Multiselect. I am using axios to do a GET request from a JSON placeholder to test.
How do I get the title and post id to show up in my drop down?
Right now, I just get [Object Object] - [title] shown in my select box.
<!-- Vue component -->
<template>
<div>
<multiselect v-model='value' :options='posts' :custom-label='postWithTitle' placeholder='Select one' label='title' track-by='id'></multiselect>
{{ value }}
</div>
</template>
<script>
import Multiselect from "vue-multiselect";
import axios from "axios";
export default {
// OR register locally
components: { Multiselect },
data() {
return {
value: null,
posts: []
};
},
created() {
this.getPosts();
},
methods: {
getPosts() {
axios
.get("https://jsonplaceholder.typicode.com/posts")
.then(response => {
// eslint-disable-next-line
console.log(response);
this.posts = response.data;
})
.catch(error => {
// eslint-disable-next-line
console.log(error);
});
},
postWithTitle(id, title) {
return `${id} - [${title}]`;
}
}
};
</script>
fix:
postWithTitle(option) {
return `${option.id} - [${option.title}]`;
}
explaination:
i saw that when i simply console.logged inside the postWithTitle function:
the custom custom-label attribute was accepting a callback that only accepts one argument. that argument was the entire option object- a single entry of your posts array.