Im a Vue/Typescript noob and I want to display data from firebase in my Nuxt3/Vue3/TypeScript app. I created a state ref with reactive that I want to initially be null or an empty object, and then when the data comes back from the axios call I want to update the value of the state.
That is all working fine but when I go to display the data in the template with a v-for I am getting "Property 'name' does not exist on type 'never'. Why am I getting that and whats the solution?
Here is what I have now:
<template>
<div class="pt-4">
<ul>
<li v-for="(person, key) in state.people" :key="key">
{{ person.name }}
</li>
</ul>
</div>
</template>
<script setup lang="ts">
import axios from "axios";
const runtimeConfig = useRuntimeConfig();
let state = reactive({
people: {},
});
onMounted(async () => {
const res = await axios.get(
`${runtimeConfig.public.firebaseBaseUrl}/people.json`
);
console.log(res.data);
state.people = res.data;
});
</script>
I tried all kinds of things but nothing seemed to fix it. The app works and runs fine but I just want to get rid of that linting error in VSCode.
You get the error because state.people
is not typed. Therefore, typescript does not expect it to be an array of objects with a name
property.
So add types for the reactive state, for example like that:
interface State {
people: YourPeopleStructure // change this to people's type
}
const state = reactive<State>({ // Here I assigned State as the reactive type
people: [], // Another fix: I assume it should be an array of people? so it has to be empty **array** by default.
});