Search code examples
vue.jsaxiosvuejs3ref

Cannot read properties of null/undefined when fetching deep nested objects


I'm currently fetching an object from an api to my vue frontend. This object has many properties, even deep nested ones. For example a project object:

{
  id: 1,
  title: "My Project",
  status: {
    text: "Planned"
    color: "Orange"
  },
  ...
}

And when fetching this object, I put it in a ref() like this:

const project = ref()
const fetchProject = async () => {
  const url = "api-url"
    try {
      const response = await axios.get(url)
      project.value = await response.data

    } catch (error) {
      console.log(error)
    }
}

Now, when I try to call a property in the html with {{ project.status.text }} it shows the Cannot read property of null/undefined. When using console.log(project) the object is fetched correctly.

Now I know, that I can use v-if to check if the property is set, but because the object is so large, I would need to add this v-if to all the elements, that need project properties. Is there a cleaner and more elegant way of solving this issue?


Solution

  • Since initially your project is empty you either put v-if around the whole template where project is used:

    <template v-if="project">
    {{ project.status.text }}
    </template>
    <div v-else>Loading project...</div>
    

    Or use optional chaining operator everywhere with possible default values:

    {{ project?.status.text ?? 'Default status' }}