The error message "Cannot read property 'data' of undefined" is commonly seen in Vue.js when using Axios

I am encountering an issue where the JSON data is not displaying in cards or list format after performing a search. The search functionality appears to be working as I can see the API call with the search text in the console. However, nothing is being displayed and I receive an error message stating TypeError: Cannot read property 'data' of undefined. It seems like there might be a problem with the JSON path.

app.vue

  <template>
  <div id="app">
    <Header/>
    <SearchForm v-on:search="search"/>
    <SearchResults
      v-if="results.length > 0"
      v-bind:results="results"
      v-bind:reformattedSearchString="reformattedSearchString"
    />
    <Pagination
      v-if="results.length > 0"
      v-bind:prevPageToken="api.prevPageToken"
      v-bind:nextPageToken="api.nextPageToken"
      v-on:prev-page="prevPage"
      v-on:next-page="nextPage"
    />
  </div>
</template>

<script>
import Header from './components/layout/Header';
import SearchForm from './components/SearchForm';
import SearchResults from './components/SearchResults';
import Pagination from './components/Pagination';
import axios from 'axios';

export default {
  name: 'app',
  components: {
    Header,
    SearchForm,
    SearchResults,
    Pagination
  },

   data() {
    return {
      results: [],
      reformattedSearchString: '',
      api: {
        baseUrl: 'https://geodeepdive.org/api/v1/articles?',
        max: 10,
        q: '',
        prevPageToken: '',
        nextPageToken: ''
      }
    };
  },


   methods: {
    search(searchParams) {
      this.reformattedSearchString = searchParams.join(' ');
      this.api.q = searchParams.join('+');
      const { baseUrl, q, max} = this.api;
      const apiUrl = `${baseUrl}&term=${q}&title=${q}&max=${max}`;
      this.getData(apiUrl);

    },

    prevPage() {
      const { baseUrl, q, max, prevPageToken } = this.api;
      const apiUrl = `${baseUrl}&term=${q}&title=${q}&max=${max}&pageToken=${prevPageToken}`;
      this.getData(apiUrl);
    },

    nextPage() {
      const { baseUrl, q, max,nextPageToken } = this.api;
      const apiUrl = `${baseUrl}&term=${q}&title=${q}&max=${max}&pageToken=${nextPageToken}`;
      this.getData(apiUrl);
    },

    getData(apiUrl) {
      axios
        .get(apiUrl)

        .then(res => {
          this.results = res.success.data;
          this.api.prevPageToken = res.success.data.prevPageToken;
          this.api.nextPageToken = res.success.data.nextPageToken;
        })
        .catch(error => console.log(error))
    }

  }
};
</script>

searchresults

<template>
  <div class="container mb-3">
    <div class="d-flex mb-3">
      <div class="mr-auto">
        <h3>Search Results for "{{ reformattedSearchString }}"</h3>
      </div>
      <div class="btn-group ml-auto" role="group">
        <button
          @click="changeDisplayMode('grid')"
          type="button"
          class="btn btn-outline-secondary"
          v-bind:class="{ active: displayMode === 'grid' }"
        >
          <i class="fas fa-th"></i>
        </button>
        <button
          @click="changeDisplayMode('list')"
          type="button"
          class="btn btn-outline-secondary"
          v-bind:class="{ active: displayMode === 'list' }"
        >
          <i class="fas fa-list"></i>
        </button>
      </div>
    </div>

    <div class="card-columns" v-if="displayMode === 'grid'">
      <div class="card" v-bind:key="result.link.url" v-for="result in results">
        <ArticleGridItem v-bind:result="result"/>
      </div>
    </div>
    <div v-else>
      <div class="card mb-2" v-bind:key="result.link.url" v-for="result in results">
        <ArticleListItem v-bind:result="result"/>
      </div>
    </div>
  </div>
</template>

<script>
import ArticleListItem from './ArticleListItem';
import ArticleGridItem from './ArticleGridItem';

export default {
  name: 'SearchResults',
  components: {
    ArticleListItem,
    ArticleGridItem
  },
  data() {
    return {
      title: 'Search Results',
      displayMode: 'grid'
    };
  },
  methods: {
    changeDisplayMode(displayMode) {
      this.displayMode = displayMode;
    }
  },
  props: ['results', 'reformattedSearchString']
};
</script>

json

{
success: {
    v: 1,
    data: [
       {
         type: "article",
         _gddid: "5ea0b2b3998e17af826b7f42",
         title: "The current COVID-19 wave will likely be mitigated in the second-line European countries",
         volume: "",
         journal: "Cold Spring Harbor Laboratory Press",
         link: [
            {
               url: "https://www.medrxiv.org/content/10.1101/2020.04.17.20069179v1",
               type: "publisher"
             }
         ],
         publisher: "bioRxiv",
         author: [
            {
               name: "Samuel Soubeyrand"
             }

         ],
        pages: "",
        number: "",
        identifier: [
          {
              type: "doi",
              id: "10.1101/2020.04.17.20069179"
           }
        ],
       year: "2020"
      }
    ]
 }

}

Answer №1

you have to include the res.data object in your code

    ensure that you are retrieving data from res.data.success.data;
    set this.api.prevPageToken using res.data.success.data.prevPageToken;
    assign this.api.nextPageToken with res.data.success.data.nextPageToken;

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 Javascript navigation functioning properly on some submenus while encountering issues on others?

If you visit , you'll notice that it's a visually appealing site. The navigation submenus seem to be functioning properly, HOWEVER upon inspecting the element, you'll notice that under the PRICING tab, there are submenus that have the same c ...

What is the best way to extract the event time when a user clicks on an event in fullcalendar?

Is there a way to extract only the time from an eventclick event in fullcalendar? Currently, I am receiving details about the event including date and time. How can I specifically retrieve just the time (e.g. 6:00:00 am)? You can find the code snippet tha ...

Utilizing Reactjs and Php to Send and Retrieve Form Data

I am currently working with Reactjs (Nextjs) and PHP. I am trying to send form data using Axios, but I am facing an issue where I am unable to retrieve any parameter on the API side. How can I resolve this problem? Below is my current code: const handleSu ...

Use Object.assign to swap out the current state with a new

Why does the React component with state { key: bool } not omit the existing state key from the new state when a different option is clicked? Link to the code var SampleComponent = React.createClass({ getInitialState: function() { return {}; }, ...

Add a JavaScript library to the header directly from the body of a webpage, ensuring it is exclusive to a single

I am using the Google Charts JS library on a single page within my project, with external and global headers and footers. The head tags are located in a head.php file, where all required JS libraries are included. The structure of my pages is as follows: ...

Exploring uncharted territory with the Navigator component in React Native

I am experiencing an issue with undefined navigator when using React Native MessageTabs: _onPressItem = (item) => { const { navigate } = this.props.navigation; //console.log(JSON.stringify(item)); navigate('SingleConversation', {id ...

Guidelines for populating data with an array

I have the following array: const dataArr = [[15, 14, 5], [16, 10, 2], [17, 6, 13], [18, 4, 8], [19, 7, 4]]; Now, I am populating another array using the above data as shown below: for (let i=0; i<dataArr.length; i++){ newData.push(dataArr[i]); ...

Searching for specific data within an embedded documents array in MongoDB using ID

While working with mongodb and nodejs to search for data within an embedded document, I encountered a strange issue. The query functions as expected in the database but not when implemented in the actual nodejs code. Below is the structure of my data obje ...

Tips for displaying all documents within a MongoDB collection using the sharedb-cli command line tool

My client-demo is not working as expected. I am trying to retrieve all documents from the "file" collection, but I am getting null results. https://i.sstatic.net/Pw6sA.png When testing with the mongo shell, I can see that the document data actually exist ...

Utilizing jQuery AJAX, we are able to seamlessly showcase information fetched from the database in CodeIgniter, moving it

I'm facing an issue with fetching data from the database using jQuery AJAX with json datatype. I've tried using JSON.parse in jQuery but it didn't seem to work. When I log data, all I see is an object returned, containing the data from the d ...

The Jquery ajax page is redirecting automatically when a post request is made

Encountering an issue while attempting to upload multiple files through AJAX, as the process redirects to a blank page displaying only the names of the uploaded files. Here is the HTML tag: Below is the JavaScript function: function upload(){ var proje ...

Create a new JavaScript object by parsing JSON data

I am looking to achieve the following: var my_data = { x : 'orange', y : 2 } function object(data){ this.x = 'banana'; this.y = 3; this.z = 'default value'; } once I have executed: var new_instance = ob ...

Making modifications to the state within a modal dialogue box

I am developing a note-taking application where users can write a title and note, and when they click submit, the note is displayed on the page. I want to implement an editing feature where clicking on the edit button opens a modal with the user's tit ...

What is preventing me from accessing the variable?

Having some trouble using a variable from JSON in another function. Can someone lend a hand? async function fetchData() { let response = await fetch('https://run.mocky.io/v3/b9f7261a-3444-4bb7-9706-84b1b521107d'); let data = await response.js ...

JavaScript utilizing a PHP variable

In my attempt to merge a PHP variable with JavaScript, I aim to access the "the_link_to_the_page_I_want". window.onload = function openWindow() { window.open('the_link_to_the_page_I_want', 'newwindow', config='height ...

Exploring the capabilities of AWS Cognito with Vue.js

I recently created a backend API using Expressjs hosted on AWS EC2. I also developed a frontend application in Vuejs that interacts with the Express API. My next step is to implement user Authorization for sign-ins, and after some research, I've deci ...

Why is my index.tsx file not properly exporting? (React + Typescript)

I've developed a basic Context Provider that I'd like to package and distribute via npm. To package my code, I utilized the create-react-library tool. In my project, I've set up an index.tsx file that should serve as the entry point for im ...

"Initiate an Ajax call in Full Calendar before an event is displayed on the calendar

I need guidance on how to integrate ajax calls with the Full Calendar documentation. Specifically, I want to make an ajax call to a WordPress database before each event is rendered on the calendar. The response from the call will determine the color of the ...

Vercel Next JS features server and client components with distinct timezones

In my Next.js 13.2.4 project, there is a useful helper function named getLocalTime(date) that retrieves the local time of the user's machine in a specific format. //Desired output: 9:30PM export function getLocalTime(date) { const localTime = new D ...

Is there a way to convert an empty string to zero in MySQL?

Can you help with answering my question? My question pertains to saving an empty string "" value in my table and storing it as a 0 value in the MySQL database. Here is a visual representation: Table -> MySQL "" 0 Thank you for your assi ...