Showcase information from APIs using Vue.js

I am facing an issue where I am able to fetch data correctly from the API, but I am unable to display it. When I manually input items, they are displayed, but the items fetched from the API remain invisible. I even attempted to move the API call directly into the ActivitiePage component, but unfortunately, no changes were observed.

Item.vue:

  <div class="item-container">
    <img :src="item.Image" alt="Item Image" class="item-image">
    <div class="item-details">
      <div class="item-text">{{ item.Text }}</div>
    </div>
  </div>
</template>

<script>

  },
  props: {
    item: Object,
  },
}
</script>

ActivitiePage:

  <div id="app">
    <ul>
        <option v-for="time in itemTimes" :key="time">{{ time }}</option>
      </select>
      <item v-for="item in items" :key="item.Text" :item="item" @share="onShareButtonClick" />
    </ul>
    <div v-if="loading">Loading...</div>
    <div v-else>
      <div v-if="items.length === 0">No items available.</div>
      <div v-else>
        <div>Items:</div>
        <pre>{{ JSON.stringify(items, null, 2) }}</pre>
      </div>
    </div>
  </div>
</template>

<script>
import Item from '@/components/Item.vue';
import SearchBar from '@/components/SearchBar.vue';

export default {
  components: {
    Item,
  },
  created() {
    fetch('/api/v1/Activities/all')
      .then(response => {
        if (!response.ok) {
          throw new Error(`Network response was not ok, status: ${response.status}`);
        }
        return response.json();
      })
      .then(data => {
        this.items = data; 
        this.loading = false;
      })
      .catch(error => {
        console.error('Error retrieving items:', error);
        this.loading = false;
      });
  },
};
</script>

Answer №1

If you're encountering an issue with a missing variable items, make sure to include a function data within the export default block. This function should return an Object containing the necessary data:

export default {
    data() {
        return {
            items: [],
            loading: false
        }
    }
}

For more information, refer to the Vue documentation provided in the link below:

https://v2.vuejs.org/v2/guide/components#data-Must-Be-a-Function

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

Tips for incorporating real-time data into your nodeJS and express applications

I am currently utilizing express for managing all the routing in my web application. Additionally, I have integrated firebase to store my data. For organization purposes, I decided to divide my code as follows: index.js: This file serves as the main node ...

"Upon invoking the console log, an empty value is being returned when attempting to access the

Why is console.log returning a blank line when trying to retrieve the value of a text input variable? HTML <label for="subject">Subject</label> <input type="text" id=" ...

Error message: When the mouse hovers over, display the chart(.js) results in TypeError: t is

I encountered a persistent error that I just can't seem to resolve. My goal is to showcase a chart using Chart.js when the mouse hovers over the canvas. However, upon hovering over the canvas, I keep getting a TypeError: t is null error. Error: { ...

Ways to organize JSON data from a fetch request into multiple divisions

I have written a JavaScript code to fetch JSON information. I plan on storing this JSON file locally (I downloaded an example file and added a birthdate object for my usage example from https://jsonplaceholder.typicode.com/users) My goal is to parse the r ...

Customize Popover Color in SelectField Component

Looking to customize the SelectField's popover background color in material-ui. Is this possible? After exploring the generated theme, it seems that there is no option for configuring the selectField or popover. Attempted adjusting the menu's ba ...

Guide for making an accordion with a close button that is specific to multiple dynamic IDs

I am looking to create an accordion feature. The idea is that when the user clicks on "Show," the text "Show" should be hidden, and the content along with a "Close" button should be displayed. Then, when the user clicks on "Close," the content and "Close" ...

Obtain a file from React Native in order to upload an image, just like using the `<input type="file" onChange={this.fileChangedHandler}>` in web development

After experimenting with different methods, I attempted to achieve the desired result by: var photo = { uri: uriFromCameraRoll, type: 'image/jpeg', name: 'photo.jpg', }; and integrating axios var body = new FormData( ...

An npm list is always full of modules

As I prepare to install a package using npm, I noticed that my folder for the new project already has numerous items listed when I run npm list. Is it normal for the folder not to be empty at this stage? Have I made an error somewhere? ...

Choosing the following choice using the Material-UI Select tool

Looking for a way to enhance my dropdown select from MUI in a Nextjs application by adding two arrows for navigating to the next/previous option. Here's what my code currently looks like: <StyledFormControl> <Select value={cu ...

Center column with header and footer flanking each side

Trying to replicate the layout of the Facebook Android app on my page. The app features a 3 column design, with the central column exclusively displaying the header (no footer included, although I require one for my version). This visual representation is ...

Is there a way for me to gain access to alter the price function within Magento?

Now, I am faced with the task of customizing the discounted price for my Shopping cart. After some independent research, I discovered that by modifying the view.phtml and item.phtml files, I can properly display the desired price. However, I still feel uns ...

Having issue updating a MySQL table using an array of objects in JavaScript

Working on a personal project involving React.js for the front-end, Node.js/express for the back-end, and mySQL for the database. The current array is as follows: horaires = [ { jour: 'Lundi', horaire: 'Fermé' }, { jour: 'Mar ...

How can I add text to a textbox within a duplicated div using Javascript or Jquery?

I'm looking to add text to a cloned div's text box using jQuery. I have a div with a button and text box, and by cloning it, I want to dynamically insert text into the new div. $(document).ready(function () { $("#click").click(function () { ...

What is the best way to activate an event listener only after a button has been clicked?

Currently, I am developing a game that includes a timer and an event listener that notifies the user not to switch tabs. However, I am facing an issue where the event listener triggers before the game's start button is clicked. Is there a way in JavaS ...

Ways to manage properties that are non-existent

Whenever vm8 encounters a property that doesn't exist, it will display an error message like this: Cannot read property 'value' of null. For example, when passing an id that doesn't exist: var pass = document.getElementById('pass ...

The Socket.io client establishes connections with multiple servers simultaneously

Imagine this scenario: I am using nodejs and socket.io, and a question comes to mind. What would happen if one client establishes connections with multiple servers like this: socket = io.connect('http://server1') //600k sockets already connecte ...

Issue: Unable to locate module 'js-yaml' while executing npm start command

Unable to locate module 'js-yaml' Require stack: D:\REACT NATIVE\portfolio\node_modules\cosmiconfig\dist\loaders.js D:\REACT NATIVE\portfolio\node_modules\cosmiconfig\dist\createExplore ...

How can a nullable variable be converted into an interface in TypeScript?

Encountered an issue while working on a vue3.x typescript project. The vue file structure is as follows: <template> <Comp ref="compRef" /> </template> <script lang="ts" setup> import {ref} from "vue& ...

What is the best way to implement rate limiting or throttling on a Strapi API?

Our company relies on a simple strapi API implemented in node.js and hosted on Heroku. Despite our efforts, we have not been able to find a solution to implement rate limiting, as it appears that Heroku does not offer throttling add-ons and strapi lacks bu ...

Issue encountered: React module not detected while attempting to execute npm start command

While developing my react app, I encountered an issue when trying to run 'npm start'. The application was working as expected until I faced a bug that prompted me to update my node version for a potential fix. After upgrading to node v16.13.2 and ...