Vue alert: Issue with rendering - TypeError: Unable to access property 'NomeStr' as it is undefined

I'm having trouble displaying the 'NameSrt' item array value in my template, and I keep encountering this issue: vue.runtime.esm.js?2b0e:619 [Vue warn]: Error in render: "TypeError: Cannot read property 'NomeStr' of undefined"

The NomeStr is located inside an object named ImagemPrincipal. Here's my code:

<table>
    <thead class="categories">
        <th><img src="../assets/bottle.svg"><p>Bebidas</p></th>
        <th><img src="../assets/pineapple.svg"><p>Frutas</p></th>
        <th><img src="../assets/cleaning.svg"><p>Limpeza</p></th>
        <th><img src="../assets/fridge.svg"><p>Congelados</p></th>
    </thead>
    <tr v-for="produto of produtos" :key="produto.IdProduto">
        <td> 
        <div v-if="(produto.lenght > 0)">
            <img class="miniatura" name="imagem" :src="produtos.ImagemPrincipal.NomeStr"/>
        </div>
            <div class="text-box">
                <p class="title">{{produto.Estoques.Produto.NomeStr}}</p>
                <p class="price">R${{produto.PrecoDoub}}</p>
                <p class="promotional">R$ 12,50</p>
            </div>
            <div class="icons-box">
                <div class="btn-favorite"></div>
                <div class="btn-add"><div class="qtd"><p>2</p></div></div>
            </div>
        </td>
    </tr>
</table> 
import axios from 'axios';

export default {
    components: {
        Cart
    },
    data () {
    return {
            info: '',
            produtos: [],
            produto: '',
            NomeStr: '',
            IdImagem: '',
            image: ''
        }
    },

    async mounted () {
      const usuario =  { UsuarioStr: "admin", SenhaStr: "abc123" };
      const url = "https://localhost:3001/api/";

    const responseLogin = await axios.post(url + 'usuarioapimobile/login', usuario);
    if(responseLogin) {
        const { data } = responseLogin.data;
        const sendData = {
          IdEntrega: 0,
          IdTipoProduto: 0,
          IdVitrine: null,
          ListaIdCategoria: [],
          ListaIdEncarte: [],
          ImagemPrincipal: [],
          NomeProdutoPesquisaStr: '',
          IdPromocao:'',
          IdProduto: 0,
          NomeStr: '',
          IdImagem: 0,
          OrdemSecao: 0
        };
        const responseData = await axios.post(url + "PromocoesGeraisMobile?idLoja=10719&pagina=0&quantidadePorPagina=150",
         sendData, { 
          headers: {'Authorization': `Bearer ${data.TokenStr}`
          }})
          .then(response => {
            this.produtos =(response.data.data.promocoesGerais)
            return { response }
          })
          .catch((err) => {
              console.error(err)
          })
        console.log(this.produtos)
        console.log('INFO', responseData)

    }
},

Can someone assist me with resolving this problem?

Answer №1

It seems like the issue lies right here...

<tr v-for="produto of produtos" :key="produto.IdProduto">
  ...
  <img class="miniatura" name="imagem" :src="produtos.ImagemPrincipal.NomeStr"/>
  ...
</tr>

Since you are utilizing v-for="produto of produtos", it appears that you're using produtos.ImagemPrincipal.NomeStr instead of produto.ImagemPrincipal.NomeStr

Just to clarify, the error is indicating that produtos.ImagemPrincipal is undefined

Without seeing the data, pinpointing the exact cause/fix might be challenging. It is likely due to mismatched structures.

To troubleshoot, I would typically do something like...

<pre>{{JSON.stringify(mytroublevar,null,2)}}</pre>

<tr v-for="produto of produtos" :key="produto.IdProduto">
    <td> 
    <div v-if="(produto.length > 0)">
        <pre>{{JSON.stringify(produto,null,2)}}</pre>
        <img class="miniatura" name="imagem" __src="produtos.ImagemPrincipal.NomeStr"/>
    </div>
        <div class="text-box">
            <p class="title">{{produto.Estoques.Produto.NomeStr}}</p>
            <p class="price">R${{produto.PrecoDoub}}</p>
            <p class="promotional">R$ 12,50</p>
        </div>
        <div class="icons-box">
            <div class="btn-favorite"></div>
            <div class="btn-add"><div class="qtd"><p>2</p></div></div>
        </div>
    </td>
</tr>

This code will display the contents of the produto object, allowing you to investigate what may have gone wrong.

Another possibility is that maybe you meant

<img class="miniatura" name="imagem" src="NomeStr"/>

¯\_(ツ)_/¯

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

Please indicate the data type in Vue using Typescript

I'm currently struggling with Vue (3) + Typescript while attempting to specify a data property with a specific type. I have created a .d.ts file, but unfortunately, it hasn't helped. This is what I'm trying: import Modeler from 'bpmn-js ...

Tips for organizing data and dynamically linking options to another select value?

One of my challenges involves working with two select elements. The first select allows for multiple options, while the second select is dependent on the choice made in the first one. <select class="form-control" id="select1"> <option value=""& ...

The dropdown menu is being filled with 'undefined' values when using AJAX as the data source in Typeahead

I've been trying to implement typeahead functionality, but I can't seem to find a solution on Stack Overflow that works for me. I am using an ajax source to retrieve JSON data for my products, however the typeahead feature is returning all matche ...

When converting a List to JSON in C#, the return value may be empty

I am facing an issue with my script. When I try to create a JSON file, it returns empty brackets {} QuizData.cs using System.Collections.Generic; [System.Serializable] public class QuizList { public string quizName; public List<QuestionList> ...

How to generate nested arrays in JSON format using MySQL data

My goal is to generate JSON using PHP from data in two MySQL tables: - Categories (unique) - Subcategories or Rights (multiple within the same category) However, I'm struggling to display multiple subcategories under one category. Currently, a ne ...

Click on the button to send the input field

Below you'll find an input field and a button: <input id="pac-input" class="controls" type="text" placeholder="Search! e.g. Pizza, Pharmacy, Post office"> <button id="new" class="btn btn-success">Submit</button> Currently, when te ...

Is there a way to secure a file in C# without rendering it unwriteable once it has been accessed for the first time

Inspired by a related thread on Stack Overflow discussing how to lock a file using C#, this question delves into the process of locking a JSON file for reading, writing, and unlocking. The proposed method involves utilizing solutions from the mentioned dis ...

Autocomplete feature integrated within search bar

I'm currently experimenting with merging MUI autocomplete and MUI searchbar to create a Searchbar that provides suggestions. I have attempted the following: https://codesandbox.io/s/material-demo-forked-cthpv import React from "react"; impo ...

Cannot locate JSON file in NodeJS

Currently, I am developing an express API and looking to establish a connection with a MySQL server using this API. The configuration settings are stored in a file named settings.json. To retrieve these settings, I am utilizing the following code: const c ...

Attempting to transmit JavaScript information to my NodeJS server

Having some trouble sending geolocation data to NodeJS through a POST request. When I check the console log in my NodeJS code, it's just showing an empty object. I've already tested it with postman and had no issues receiving the data. The probl ...

The usage of ngRoute clashes with the functionality of Animated Scroll

I am experiencing a conflict between my ng-route and the animated scroll feature on my website: Below is the code for my scroll element: <a href="#one" class="goto-next scrolly">Next</a> In this code, "#one" represents the section ID to scro ...

Having trouble getting a ForEach loop to work within promises when using mongoose?

Hey everyone! I'm diving into the world of nodeJs and working on a project that involves pushing certain values into an array. Unfortunately, my code isn't behaving as expected, and I suspect it has something to do with promises. Here's the ...

Nuxt 3.11 - Best Practices for Integrating the `github/relative-time-element` Dependency

I'm encountering some difficulties while attempting to integrate github/relative-time-element with Nuxt 3.11.2 and Nitro 2.9.6. This is my current progress: I added the library through the command: $ npm install @github/time-elements. I adjusted nux ...

Identifying whether a Property in an Object is another Object

I'm planning to utilize JSON for stringifying the value of a property within an object, which will then be stored as a Tag on Google Calendar using Google Apps Script. The value in question is actually a double-nested Object (look at extraAttributes w ...

How to remove an image input type using jQuery

Can anyone provide insight into the issue with these scripts? I am attempting to remove an input when it is clicked. The input is of type image, so CSS cannot be used. I have tried using JavaScript but it doesn't seem to be working. HTML <!doctyp ...

Issues arise when using bootstrap-multiselect onDropdownShow

I am currently utilizing the bootstrap-multiselect plugin created by davidstutz in conjunction with twitter bootstrap 3.3.0. My goal is to have a radio button selected when I click on the dropdown, however, this functionality does not seem to be working a ...

Navigating after submitting a form using the Location header in jQuery

Seeking a way to utilize the Location header in jQuery 1.7 for redirection to a target. The current code is structured as follows: $('#creationLink').click(function(){ $.ajax({ type: 'POST', url: '/', success: ...

What is the process for integrating an array into an existing JSON file?

I'm struggling with inserting an array into an existing JSON file using PHP. Here's the code I currently have: $profile = file_get_contents("http://api.steampowered.com/ISteamUser/GetPlayerSummaries/v0002/?key=0CDB935B8BFF1E1664C90DB875E88727&am ...

MongoDB Integration of Collections - No Data Population

Having trouble merging a client and an account collection. When I use res.send(client), only the account id's are returned. Unsure how to include account information in clients. Have seen one to many solutions, but struggling with this two-way relati ...

Leveraging numerous identifiers in jQuery

I created a small jQuery script to check if the input box value is greater than 5, but I have two tags with IDs and only one of them seems to be working. <div id="register"> <form id="register"> <input id="first" type="text" /> <a ...