Error thrown by computed property despite its functionality

I have a code snippet that retrieves data from an external server, which is triggered when the component is mounted

var get_one = 'https://api.example.com/rb.php';           
  axios.get(get_one)
            .then(response => {   
               // console.log(response.data);
                var data = response.data;
                    this.roomsData = data;
                    this.room_name = response.data.room_name;
                this.roomsData.room_photos = response.data.room_photos;
            })
            .catch(e => {
                this.errors.push(e)
            }); 

Upon refreshing the page, {{roomsData.room_photos}} displays the following content

[ { "url": "/var/www/html/uploads/609cd3aaaaefd.jpg" }, { "url": "/var/www/html/uploads/609cd3aaa9dc2.jpg" }, ... 

This is my computed function:

computed: {
  image_viewer_data: function () { 
  let vd = this.roomsData.room_photos
  console.log('inside computed',vd)
  
  let modifiedArr = vd.map(function(item){
  let url_parts = item.url.split('/')
  return 'https://api.example.com/uploads' + '/' + url_parts[url_parts.length - 1]
   });
return modifiedArr;
    }
 },

When I output {{image_viewer_data}}, it appears in the format shown below:

[ "https://api.example.com/uploads/609cd3aaaaefd.jpg", "https://api.example.com/uploads/609cd3aaa9dc2.jpg", ... 

This is how I am utilizing this computed function:

<div class="carousel-item" v-for="(value,index) in image_viewer_data"   >
      <img class="d-block w-100"  :src="value" :id="index" >
 </div>

However, upon page refresh, I encounter the following errors:

[Vue warn]: Error in render: "TypeError: vd.map is not a function

and

TypeError: vd.map is not a function

It perplexes me as to why the code works intermittently and also fails at the same time.

Answer №1

The warning message indicates that `vd` is not recognized as an array, hence the `map()` function cannot be applied. However, it still works because the object you are using is iterable and behaves like an array.

To resolve this, you can try creating a new array instance by utilizing Array.from():

let vd = [ { "url": "/var/www/html/uploads/609cd3aaaaefd.jpg" }, { "url": "/var/www/html/uploads/609cd3aaa9dc2.jpg" }, { "url": "/var/www/html/uploads/609cd3aab1252.jpg" }, { "url": "/var/www/html/uploads/609cd3aab147a.jpg" } ] 
let modifiedArr = Array.from(vd).map(function(item){
          let url_parts = item.url.split('/');
          return 'https://api.example.com/uploads' + '/' + url_parts[url_parts.length - 1];
       });
console.log(modifiedArr);

Answer №2

It appears that the variable vd is not being recognized as an array, hence resulting in errors. Ever wondered why this happens? One possible cause could be that your code is trying to access vd.map before the data has finished loading.

To resolve this issue, it would be beneficial to add a null check before attempting to access vd. For example:

 let newArr = vd?.map(element=>{
...
...
}) || [];

This approach will ensure a seamless integration of the solution.

In a general coding convention,

let newArr = vd && vd.map() || [] 

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

Rotating the camera in a 2D space using three.js

Within my app, I have implemented a camera: camera = new THREE.PerspectiveCamera( 75, window.innerWidth / window.innerHeight, 0.1, 1000 ); camera.position.z = 1; camera.position.y = -5; camera.rotateOnAxis(new THREE.Vector3(1, 0, 0), degInRad(90)); camera ...

Arrange an array that has been sifted through

I'm having trouble figuring out where to place the .sort() method in the code snippet below. I've tried multiple placements but it either gives errors or doesn't work as intended. My goal is to sort the list alphabetically in this scenario. ...

Looking for a simple method to link JSON data to an svg element through Javascript?

Looking to harness the power of SVG for a basic graph creation, but uncertain about the process of assigning JSON data dynamically using a 'for loop' to draw rectangles within SVG. Seeking guidance on setting up 1 loop to assign each value for dr ...

Troubleshooting the issue with rotating Three.js boxes towards the mouse pointer

I am facing an issue with rotating several randomly generated boxes towards the mouse position. Even after trying to use lookAt(mouse3D) method, the boxes do not change their rotation as expected. My goal is to have the boxes rotate towards the mouse posit ...

Unexpected Error in Vue JS: Array IndexOf is not a Function

Every time I've needed to verify if a number exists in an array, I rely on using .indexOf(), but for some reason, it's not working this time around. Vue method showSeat(seat) { if( !this.selectedSeats.length ) { this.selectedSeats. ...

Inquiring about JavaScript's substring method in String.prototype

let vowels = "AEIOU"; let result = vowels.substring(0, 3); document.write(result); I'm puzzled as to why the output is AEI instead of AEIO. Is this due to the indexing starting from zero in programming languages? ...

What causes dates to shift by 24 hours?

I am facing an intriguing datetime dilemma. It seems like I just can't crack it and it's driving me crazy. Perhaps I overlooked something or didn't approach it in the right way. Currently, I am retrieving data from Mongo using Axios. The da ...

The front-end is responsible for removing the last item from an array

Having an issue with my React code. Here is my parent component: class RoomPrice extends React.Component { constructor(props){ super(props) this.state = { room: this.props.room, prices: [] }; this.handleDeletePrice = this.h ...

Is the vertex count of a Geometry in Three.js increased when it is converted to a BufferGeometry?

Recently, I've been experimenting with the fromGeometry method to convert regular Geometry objects into BufferGeometry objects. To my surprise, I noticed that the number of vertices increases during this conversion process. For instance, consider the ...

"Unlocking the Power of Social Interaction with Vue.js

I've successfully integrated a Facebook Login module in my project and it's working well. However, I'm facing difficulties when trying to link the response data with an input field. Can someone guide me on how to achieve this? I'm still ...

Transferring information from a single document to numerous documents

I have been developing an internal webpage to streamline email automation tasks. Currently, I have created a basic form that contains general information which will be consistent across all subsequent forms. Additionally, there are multiple customized form ...

Ways to align this element in the middle

<div id="1" style="display:block"> <div class="radio"> <label><input type="radio" name="o1"> <input type="text" class="form-control" id="opt1"></label> </div> <div class="radio"> <label>< ...

Troubleshooting Problem with Integrating ControllerAs in AngularJS Routing and Application.js

Can someone please help identify the errors in the code? Issue 1: The Save button in addstudent.html is not functioning properly. It works with $Scope, but after modifying the code to use ControllerAs, the functionality ceased. Debugging revealed that con ...

Stripping CSS prefixes upon file initialization

When developing my application, I have a process in place where I load CSS files on the back-end using Express.JS and then transmit them to the front-end. However, before sending the CSS code to the front-end, I need to: Identify the user's browser; ...

Dealing with TypeScript issues while implementing Multer in an Express application

import multer, { FileFilterCallback } from "multer"; import sharp from "sharp"; import { NextFunction, Request, Response } from "express"; const multerStorage = multer.memoryStorage(); const multerFilter = ( req: Request, ...

What is the best way to switch a single class using jQuery without impacting other elements with the same class

I'm in the process of implementing a commenting system similar to Reddit on my website. Each comment is equipped with a small button in the top right corner that allows users to collapse the comment. To achieve the collapsing effect, I am utilizing j ...

What is the best method for retrieving objects from a Meteor collection?

I'm a beginner with Meteor and I'm currently working on the introductory tutorial. However, I'm facing difficulties in retrieving data from a collection. Below is my JavaScript code: import angular from 'angular'; import angularM ...

Unable to automatically close Vue-strap after a set time period

I've implemented the Vue-strap alert component in my Vue.js project and it's working well. However, I'm facing an issue with automatically closing the alert box after a specified duration. Below is the code snippet of the component I am curr ...

Is there a way for me to determine the proportion of my tests that are covered?

I am eager to determine the coverage of my project through my tests, and I am currently experimenting with the use of jest for this purpose. Here is the content of my jest.config.js: module.exports = { verbose: true, preset: '@vue/cli-plugin-unit ...

What steps should be taken to develop a Hybrid Mobile App concept?

We are currently developing our first hybrid mobile application with a monetizable idea in mind. After conducting some research, it seems that to reach our end goal we will need: A Front End UI Framework: options include Ionic or AngularGap (although d ...