Reputation: 374
im using axios to fetch some json from my django backend, the api call works and i can see the results when i console.log them
for some reason when i load the page i get an error that my data in undefined but i if comment out the code where my data gets displayed in the template it dosnt give me any errors
when i un-comment that code, vite reloads my browser and the data gets diplayed properly until i refresh
why does this happen and how can i fix this
heres my code
<script setup>
import { ref, onMounted, watch } from "vue";
import { useProductsStore } from "../stores/products";
import { useRoute } from 'vue-router'
import axios from 'axios'
const store = useProductsStore();
const route = useRoute()
let id = route.params.id
let deets = ref({
name: "Loading",
description: "Loading",
sku: "Loading",
asin: "Loading"
})
let link = "http://127.0.0.1:8000/products/" + id
async function getDeets(link) {
try {
const data = await axios.get(link)
deets = data.data;
console.log(deets)
} catch (error) {
console.log(error);
}
};
onMounted(() => {
getDeets(link)
})
</script>
<template>
<div class='deets'>
<h1>Product Details</h1>
<hr>
<h2>Name: {{ deets.name }}</h2>
<h3>Description: {{ deets.description }}</h3>
<h2>Sku: {{ deets.sku }}</h2>
<h3>Asin: {{ deets.asin }}</h3>
<!-- <h3>{{ deets.price }}</h3> -->
</div>
</template>
<style scoped>
.deets {
text-align: left;
}
</style>
i am having a similar problem on a different component and i suspect its because by the time the browser renders the template my api call hasnt run yet so therefore it IS undefined but when vite does a hmr update it works
my other component shows a table of all the products in my db and it works fine unless im navigating back to that page in which case it dosnt display the data until i refresh
Upvotes: 3
Views: 272
Reputation: 398
Your code is wrong in 3 places. Wrong places are marked with //wrong and corrected.
<script setup>
import { ref, onMounted, watch } from "vue";
import { useProductsStore } from "../stores/products";
import { useRoute } from 'vue-router'
import axios from 'axios'
const store = useProductsStore();
const route = useRoute()
let id = route.params.id
const deets = ref({ //wrong
name: "Loading",
description: "Loading",
sku: "Loading",
asin: "Loading"
})
let link = "http://127.0.0.1:8000/products/" + id
async function getDeets(link) {
try {
const data = await axios.get(link)
deets.value = data.data; //wrong
console.log(deets.value) //wrong
} catch (error) {
console.log(error);
}
};
onMounted(() => {
getDeets(link)
})
</script>
<template>
<div class='deets'>
<h1>Product Details</h1>
<hr>
<h2>Name: {{ deets.name }}</h2>
<h3>Description: {{ deets.description }}</h3>
<h2>Sku: {{ deets.sku }}</h2>
<h3>Asin: {{ deets.asin }}</h3>
<!-- <h3>{{ deets.price }}</h3> -->
</div>
</template>
<style scoped>
.deets {
text-align: left;
}
</style>
The ref data in the script section needs .value to access. Also, the ref type must always be const.
Upvotes: 0