The v-for directive fails to display the contents of the array

I would like to display some data received from the server in a loop:

The JSON data that I have received looks like this (seen in the browser console):

fetched data is: 
{projs: Array(10), page_number: 1, total_pages: 1}
page_number: 1
projs: Array(10)
0: {typ: 1, ttl: 'Ada gwgwe', slg: 'Ada-gwgwe', dsc: ' Qui qui voluptas bla', skls: Array(2), …}
1: {typ: 3, ttl: 'Aut magna consequatu', slg: 'Aut-magna-consequatu', dsc: 'Reiciendis nobis omn', skls: Array(1), …}
2: {typ: 2, ttl: 'Perferendis itaque p', slg: 'Perferendis-itaque-p', dsc: 'Perferendis velit a', skls: Array(1), …}
3: {typ: 1, ttl: 'Cumque sint maiores ', slg: 'Cumque-sint-maiores-', dsc: '        Rerum a nemo consequ', skls: Array(4), …}
length: 4
[[Prototype]]: Array(0)
total_pages: 1

Here is my Vue.js code on a single page:

 const vueApp = new Vue({

     delimiters: ['${', '}'],
     el: '#projs-container',
     data: {
         base_url: 'http://127.0.0.1:8080',
         display: 'this is rendered fine',
         projects: [],
         projs: [],
     },
     created() {
         // GET request using fetch with error handling
         fetch("http://127.0.0.1:8080/projects-json")
             .then(async response => {
                 const projects = await response.json();
                 console.log('fetched data is:', projects);
                 let projs = projects.projs;
                  // check for error response
                 if (!response.ok) {
                     // get error message from body or default to response statusText
                     const error = (data && data.message) || response.statusText;
                     return Promise.reject(error);
                 }
             })
             .catch(error => {
                 this.errorMessage = error;
                 console.error("There was an error!", error);
             });
     },
     methods: {
 

 });

HTML:

<div id="projs-container">
                     <p>Hello World. ${ display }</p>
                     <ul id="projs-loop">
                         <li v-for="p in projs" :key='projs.slg'>
                             ${ p.ttl }
                         </li>
                     </ul>

However, to my surprise, nothing is being displayed in the loop. What could be going wrong here? How can I rectify this issue?

Answer №1

Instead of assigning the result from the fetch in the state, you have defined it locally with a let projs.

To use it in the template, you need to add the result to the state of your app.

const vueApp = new Vue({

     delimiters: ['${', '}'],
     el: '#projs-container',
     data: {
         base_url: 'http://127.0.0.1:8080',
         display: 'this is rendered fine',
         projects: [],
         projs: [],
     },
     created() {
         // GET request using fetch with error handling
         fetch("http://127.0.0.1:8080/projects-json")
             .then(async response => {
                 const projects = await response.json();
                 
                 // check for error response
                 if (!response.ok) {
                     // get error message from body or default to response statusText
                     const error = (data && data.message) || response.statusText;
                     return Promise.reject(error);
                 }
                 
                 console.log('fetched data is:', projects);
                 this.projs = projects.projs; // ensure to review this line here
                  
                 
             })
             .catch(error => {
                 this.errorMessage = error;
                 console.error("There was an error!", error);
             });
     },
     methods: {
 

 });

I haven't checked the rest of the code, but this adjustment should help you move forward

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

How can we nest a div within the outermost parent element?

Consider a scenario where there are 3 different divs named grandParent, Parent, and Child. Although the parent's tag is placed inside the grandParent, due to the use of position: absolute; property, the parent ends up being displayed outside the grand ...

Using either Javascript or JQuery to update every cell in a particular column of a table

I need to use a button to add "OK" in the Status column of table tblItem, which is initially empty. How can I achieve this using JavaScript or JQuery? The table has an id of tblItem Id Item Price Status 1 A 15 2 B 20 3 C ...

Mix up the colors randomly

After searching extensively, I have been unable to find exactly what I am looking for. The closest matches only cover a portion of my needs which include: I am seeking a randomly selected color scheme that I have created but not yet implemented in code. T ...

Retrieving values from multiple Select components in Material-UI is key

I have encountered an issue with my two MUI Select components on the page. I am attempting to set values based on the id of the Select component. Initially, when I check (id === "breed-select") in the console, it returns true, but shortly after ...

Calculate the length of a JSON array by using the value of one of its

What is the most efficient way to obtain the length of a JSON array in jQuery, based on the value of its attribute? As an illustration, consider the following array: var arr = [{ "name":"amit", "online":true },{ "name":"rohit", "online":f ...

Tips for using "scoped" styles effectively in VueJS single file components

The documentation for VueJS states that the scoped attribute should restrict styles to a specific component. However, I noticed that if I create two components with the same baz style, it leaks from one component into the other: foo.vue <template> ...

The data-src tags are functioning properly in the index.html file, but they are not working correctly in angular

I'm still learning about Angular and JavaScript, so please bear with me if my questions seem silly. I've been trying to add a theme to my Angular project. When I include the entire code in index.html, everything works fine. However, when I move ...

How can one determine the number of characters that remain visible once text-overflow:ellipsis and overflow:hidden are implemented?

How can I display a list of email addresses separated by a delimiter ';' while preserving the original format? I also need to cut off any overflow text that exceeds one line, and then indicate the number of email addresses remaining that the user ...

The information from AngularJS is not appearing in the table

I am currently developing a web application that utilizes AngularJS for SQL connectivity. While working on my project, I encountered an issue where the data for the "Regional Partner Manager" user is not displaying properly in my table, whereas the data f ...

Ways to monitor the status of a server request using jQuery (ajax)?

I am currently working on a PHP application that involves users submitting forms to the server via ajax (jQuery). The server needs to insert a large number of records into a MySQL database, which may take some time due to various calculations. My question ...

Encountered an error due to an unexpected { token while attempting to

I'm working on my react code and have come across an issue with the following method that is supposed to return a hash: foo: function() { return {{a: 1,b: 2,c: 3}, {d: 4}}; } But when I reach the line with the return statement, I keep getting t ...

Extract the selected date from the datepicker and showcase it within a designated div element

I need to retrieve the selected date from a jQuery UI datepicker and show it in two places on the page. Currently, the selected date is displayed in the input field of the datepicker, but I also want to display it within a div tag elsewhere on the page. ...

How to Traverse Through Every Element in a For Loop with NodeJS

I am currently working on developing a full-stack application using Express and Mongoose on the backend. To better illustrate my goal, I will provide an image to give you a clearer understanding. https://i.sstatic.net/T5x8C.png The issue I am facing is d ...

How to showcase an item appended to an array within a nested component using Vue.js

Working with Vue, I have a scenario where a component in my parent App.vue displays the contents of an array called ListofLists. When I push new data to this array, how can I ensure that the display list component reflects the updated data? In one of my c ...

Scroll upwards within a nested div

Is there a way to smoothly animate the content of the inner div upward without requiring any button clicks? Also, is there a method to trigger an event once the animation has completed? ...

Include web browsing history

In my ASP.Net/VB project, I am facing an issue with floating DIVs. Whenever users try to close the floating DIV by clicking on the back button in their browser, it creates a confusing experience. My solution is to add a "#" entry to the browser history wh ...

To display table data in Vue 3, simply append a hashtag to the end of the address

I am facing an issue with rendering data to a table. Although I receive the data in the console, it does not appear in the table unless I add a '#' to the end of the address like: http://localhost:81/realstate# Alternatively, if I make a change ...

Retrieving Information From External Script Using JavaScript

Struggling with exporting/importing script from model.js, I've used the following code: import * as model from './model.js'; Below is the code snippet from model.js: export const state = { recipe: {}, }; console.log(state.recipe); export ...

The specified class is not found in the type 'ILineOptions' for fabricjs

Attempting to incorporate the solution provided in this answer for typescript, , regarding creating a Line. The code snippet from the answer includes the following options: var line = new fabric.Line(points, { strokeWidth: 2, fill: '#999999', ...

What is the best way to access the front camera on both Android and iOS devices in order to capture a photo using Vue.J

I am currently developing a PWA Vue.Js application and I am trying to implement a feature that allows users to take a picture with the front camera on their mobile devices. Although I have managed to write code that works on my desktop browser, I have bee ...