Currently, I'm facing some challenges with my Vue 3 app in terms of getting things to work as expected.
The main issue lies in properly accessing a reactive array. Let me provide you with the code for better comprehension:
Within my global store store/questions/index.js
, I have the following code snippet:
const useQuestionsAndAnswers = () => {
const data = reactive([])
const getQuestionsAndAnswers = async () => {
const response = await fetch('../../../db/questions.json')
const fetchedData = await response.json();
if(response.status === 200) {
fetchedData.data.forEach(obj => data.push(obj))
console.log(data[0]); <--------- // The console.log here works fine
} else {
console.log('Something went wrong')
}
};
onMounted(() => {
getQuestionsAndAnswers();
});
return { data }
}
export default useQuestionsAndAnswers;
Upon running console.log(data[0])
, I am able to retrieve the desired object. Therefore, it seems like this part is functioning correctly.
My objective is to utilize this data within a Vue component. Here lies the implementation of the component:
components/calculator/Questions.vue
:
<template>
<div class="block max-w-4xl" v-if='data'>
<h3 class='py-4'>Select the option that best describes you</h3>
{{ data[0] }} // Equivalent to the previous console.log statement.
</div>
</template>
<script>
import useQuestionsAndAnswers from '../../store/questions/index.js'
export default {
setup() {
const { data } = useQuestionsAndAnswers();
console.log(data)
return {
data,
}
}
}
</script>
However, issues arose at this stage. While displaying the {{ data[0] }}
bindings in the DOM functions as intended, attempting to access the question
key with data[0].question
results in displaying the data correctly initially but becomes undefined upon page refresh. It appears that reactivity might be missing.
An additional complication occurs within the setup()
function. Although console.log(data)
returns the anticipated Proxy
containing my array
, trying to access an object within the mentioned array using console.log(data[0])
once again produces undefined
.
To illustrate, I will provide an example of the JSON data I am receiving:
{
"data": [
{
"question" : "You are amidst a worldwide pandemic and decide to nationalize a well-known food company (its name starts with V for Vicentín) that has not paid its creditors for years. How would you handle Clarín's criticism?",
"image": "@/assets/alberto.png",
"id": 1,
"answers": [
{
"id": 1,
"answer": "I would act tough for a few days and then step back.",
"points": 2,
"slug": "act-tough"
}
]
}
]
}
In essence, what I aim for is seamless access to the array elements and the ability to display the desired information accurately.
Thank you for your help!