What steps can be taken to extract data from an axios call within a computed method for further manipulation?

Utilizing an axios call, I retrieve data in the following format:

  export default {
      name: 'TaxesSection',
      data () {
        return {
          isFormShown: false,
          isLoading: false,
          isOpen: false,
          info: null,
          dist: null,
          tableauDistance: [],
          tableauGeneral: {},
          tabName: [],
          tabProrataDist: [],
          tabPriceHt: [],
          voyages: {},
          id: null,
          amount: null,
          errors: []
        }
      },
      // This fetches posts upon creation of the component.
      async created() {
        try {
          const response = await axios.get(`/cruise/${this.cruise.id}/vat_info`)
          this.info = response.data
        } catch (e) {
          this.errors.push(e)
        }
      },
      props: ['agreementId'],
      computed: {
        getTotalDistance () {
          return this.info
        },

When I render the HTML data by calling {{getTotalDistance}}, the output is as follows:

{ "disembs_vat": [ { "profile": ... , "write_access": true } ] ], "qualifying_voyages": [ { "end_wp_id": 23, "qualifying": false, "start_wp_id": 1 }, ... ] 

However, when attempting to manipulate the data within the computed function "getTotalDistance" and trying to return this.info.disembs_vat or make any modifications, I encounter the following error:

vue.runtime.esm.js?2b0e:1897 TypeError: Cannot read properties of null (reading 'disembs_vat')
    at VueComponent.getTotalDistance (TaxesSection.vue?b2b5:43:1)
    ...

I have been unable to solve this issue... It seems to work when making small modifications and saving the changes but not when refreshing the page with F5.

Appreciate any help!

Answer №1

Prior to the completion of your request (and filling in this.info), the value of this.info is currently set to null.

The error message indicates that null does not possess a property named disembs_vat, which is indeed accurate.

To address this issue, utilize optional chaining to retrieve the value of this.item.disembs_vat only when item is truthy, and return undefined otherwise:

<script>
export default {
  // ...
  computed: {
    vat() {
      return this.item?.disembs_vat
    }
  }
  // ...
}
</script>
<template>
  <pre v-text="{ vat }" />
</template>

If you prefer not to receive undefined when the item is null, you can specify a default value as shown below:

this.item?.disembs_vat || 'default value here'

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Is your child component releasing data?

Currently, I am facing an issue with my child component where the data changes are not being emitted properly. Here is how I am trying to handle it: <input type="checkbox" value="john" v-model="users" @click="updateUsers"> Upon clicking on the chec ...

What is the best way to show a filtered list using a state that was created with useState in React?

Check out my code in CodeSandbox, consisting of 4 divs categorized as "Book" and "Article". There are buttons at the top to toggle between displaying all divs, only books, or only articles. However, clicking on any button currently shows all divs and gives ...

Ensuring that undefined is not present before making an API request is crucial in the componentWillMount lifecycle

When I have a component that triggers methods depending on asynchronous API requests, I check certain props using componentWillmount. If a specific prop is true, I trigger a function; otherwise, I do not. The issue arises when the prop is initially undef ...

Making a POST request to a local node.js script

This question might be a beginner one. I'm a newcomer to the world of node.js. Currently, I am working on a script that needs to handle HTTP POST requests. As I am planning to deploy it on Heroku eventually, I wonder how can I test these POST reques ...

Adding / Deleting a Row in a sequence of floated divs

I have a group of div elements arranged side by side with the float:left style as shown below: <div id="container"> <div id=0" style="float:left">> Stuff </div> <div id=1" style="float:left">> Stuff </div> < ...

The returned value is indeterminate

I have a Node.js project with a main file named index.js and a helper file named helper.js. The helper file contains some functions that are imported into the main file. I am trying to retrieve some data using a function from the helper.js file, but when I ...

Send query string parameters to retrieve data within a specific updatedAt timeframe

How can I retrieve data based on a specified range of month/week/days it was last updated? this.userDetails = async (req) => { try { let updatedAt = req.query.updatedAt let start = moment().startOf('day') let end = ...

Utilizing the power of $.ajax() to parse through an XML document

I have a query about working with a large XML file containing 1000 nodes. Here is the code snippet I am using: $.ajax({ type: "GET", cache: false, url: "someFile.xml", ...

Guide to setting up a hit counter in the MEAN stack framework

QUERY: Is there a way to track the number of hits on each post by a user? I want the count to increase for every unique visitor who sees the post. While I can update and save the count on the server side, how can I restrict it by IP address and prevent ...

There is no need for blank space when using the JSF inputtext component

When using a jsf form with required inputs, checking for empty spaces can be important. Utilizing the required="true" attribute helps, but it's also necessary to prevent users from submitting forms with just empty space characters entered. One approac ...

Having trouble running `npm run dev` due to a webpack/babel conflict?

While attempting to execute npm run dev for a Vue project, I am consistently encountering the following output: npm ERR! code ERESOLVE npm ERR! ERESOLVE could not resolve npm ERR! npm ERR! While resolving: [email protected] npm ERR! Found: [email ...

What could be the reason for my Node.js Express response coming back as empty?

While working on a registration system, I have encountered an issue. When errors occur in the form, I receive the correct error messages. However, when a user with the same email attempts to register and triggers 'res.json({error: 'email exists& ...

Sorting data in Javascript can be done efficiently by utilizing the .filter method

Can someone help me identify what I might be doing incorrectly? I have a chained filter under computed that is giving me an error message stating 'product.topic.sort' is not a function. My intention is to use 'select' to provide sortin ...

Display the bash script results on an HTML webpage

My bash script fetches device status and packet loss information, slightly adjusted for privacy: #!/bin/bash TSTAMP=$(date +'%Y-%m-%d %H:%M') device1=`ping -c 1 100.1.0.2 | grep packet | awk '{ print $6 " " $7 " " $8 }'` device2=`pin ...

Encountering an error when attempting to authenticate a user with Amazon Cognito in React JS: "Unable to assign values to undefined properties (specifically 'validationData')."

While I have some experience with JS, I admit I'm not an expert. That's why I'm reaching out here for help. I recently started working on a website using React and ran into an issue when trying to authenticate a user against Amazon Cognito u ...

I encounter an error when I link or embed a middleware within another

I am facing an issue while trying to implement a nested middleware within another middleware. Upon calling the nested middleware, I encounter the following error: Error [ERR_HTTP_HEADERS_SENT]: Cannot set headers after they are sent to the client Below ...

An issue has occurred: function() is not a valid function

Issue: core.mjs:10132 ERROR TypeError: block.getDepartment is not a function at FirebaseService.mapDatabaseToBlock (firebase.service.ts:54:30) at firebase.service.ts:45:60 at Array.map (<anonymous>) at firebase.service.ts:45:42 at ...

Is it possible to generate distance between 2 elements without utilizing padding or margin?

In my React Native project, I'm currently working with 2 inline buttons - the search and add buttons: https://i.stack.imgur.com/tKZrf.png I'm looking to add some spacing between these buttons without impacting their alignment with the left and ...

Display information from dynamically generated pages using Gatsby JS sourcing data from CSV files

I've been working on creating pages in Gatsby JS from a csv file and everything seemed to be going smoothly. However, when it comes to displaying the data on these generated pages, I keep running into issues with undefined variables and can't see ...

Utilize Angular components in TypeScript to effectively manage errors within forms

I am currently developing a form in Angular/Typescript with more than 10 fields, and I want to streamline error management without redundancy in my HTML code. Here is an example of the form structure : <form [formGroup]="myForm"> <label&g ...