Building out an ecommerce store. Started with the products, which require no auth to pull, but do require auth to edit. This is working fine, and I suspect it's because this is happening on the client which sends auth info with all requests direct from client (ie methods hook).
However, order data does require auth to access any of it. I'm unable to access this route to generate the page using asyncData. I suspect this is because it's happening on the Nuxt server instead of on the client.
async asyncData({ $config: { apiURL } }) {
let orders = await axios.get(
`${apiURL}/orders`
);
return { orders: orders.data.data };
},
What is the correct way to do this? Set an empty data point then use mounted or created to pull and set?
Update: I got it working with as a method, but then you have to press the button to pull all the orders, that's pretty bad ux lol what do
CodePudding user response:
An alternative solution would be
<template>
<section>
<div v-for="user in users" :key="user.id">
{{ user.name }}
</div>
</section>
</template>
<script>
export default {
async asyncData({ $axios, $config: { jsonPlaceholder } }) {
const fetchedUsers = await $axios.$get(`${jsonPlaceholder}/users`)
return { users: fetchedUsers }
},
data() {
return {
users: [],
}
},
}
</script>
This is using JSONplaceholder as an example, in your case you may add an additional data
as you did initially.
This solution has the benefit of blocking the render of the page until the call is done (mounted()
cannot).
CodePudding user response:
Got it working, this is what I did:
data: () => ({
orders: []
}),
mounted() {
this.$axios.$get(`${this.$config.apiURL}/orders`).then( res => {
this.orders = res.data
})
},
Let me know if there's a better way to go