Utilizing database information for interactive objects in Three.js: A step-by-step guide

I need to display specific text data for each object based on database entries in my project. However, despite creating a cube for each entry in the database, I'm encountering issues with undefined data. It seems like my code should work, but it's not.

  getData()

  async function getData() {
        try {
            var response = await fetch('/api/indexvr');
            var data = await response.json();


            for (var i = 0; i < data.length; i++) {
                cube = new THREE.Mesh(geometry, material.clone());
                cube.userData = {
                    id: data.id,
                    URL: `/vr/${data.id}/`,
                    title: data.title, 
                    description: data.description
                    };
                cube.position.x = i;
                scene.add(cube);
                console.log(cube.userData) 
                //group.add(data)
            }
        } catch (e) {
            console.error(e)
        }
  }

The code above is used to retrieve information from my MongoDB collection, which includes file paths along with titles, descriptions, and labels for each file.

After researching, it appears that using 'userData' is the recommended approach for storing additional object information in Three.js.

Currently, I am able to change the color of objects when hovering over them with Raycasting. Once I resolve this issue, I plan to implement functionality that displays the title when an object is hovered over and redirects to the corresponding URL when clicked.

As a newcomer to three.js, I find the process quite challenging.

Answer №1

It seems like there may be some confusion with the structure of the data variable. At times, it is being treated as an object, while at other times it is being treated as an array.

For instance, if you are using data.length in your for loop, then data must be an array. You cannot directly access properties like .description or .title on an array itself. Instead, you would need to access these properties within each element contained within the array, such as data[0].description, data[1].description, and so on.

// Create a variable to reference
// the current element during array looping
var arrayElement;

for (var i = 0; i < data.length; i++) {
    // Obtain the element for this iteration
    arrayElement = data[i];

    cube = new THREE.Mesh(geometry, material.clone());

    // Now, you can access information within the current array element
    cube.userData = {
        id: arrayElement.id,
        URL: `/vr/${arrayElement.id}/`,
        title: arrayElement.title, 
        description: arrayElement.description
    };
    cube.position.x = i;
    scene.add(cube);
    console.log(cube.userData)
}

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

Extract string data from JSON payload

How can I extract the itemlocation from itemInfo and display it in a new column in my react table using Material UI? While I know this can be done on the backend, I am looking for a way to achieve this without backend involvement. Below is an example of ho ...

Discovering absent data in JSON with the help of Python

I'm encountering an issue where I need to categorize a dataset into completed and incomplete sections. To achieve this, I aim to insert flags like 'complete' in the JSON data structure, as shown in the example below. Here is the dataset tha ...

In search of specific categories within a JSON document online

Struggling to understand how JSON and Java objects work together. My task is to check a JSON file at a URL for any available software updates. I've managed to establish a connection and print the JSON data to the console, but that's as far as I&a ...

default selection in AngularJS select box determined by database ID

Here is the scenario: ... <select ng-model="customer" ng-options="c.name for c in customers"> <option value="">-- choose customer --</option> </select> .... In my controller: $scope.customers = [ {"id":4,"name":"aaaa", ...

Is it possible to enhance Vector Accuracy in THREE.js?

While working in THREE.js, I have encountered situations where I wish for improved control over vector precision, especially when dealing with large floating point numbers in scenarios like a solar system. Is there a way to address this challenge effective ...

Material-UI: Error - getMuiTheme function is not defined

After recently updating my material-ui to version 0.15.4, I encountered an issue while trying to make it work. The error message states that getMuiTheme is not a function, despite the fact that the relevant JavaScript file is present in the folder location ...

Page encountering NextJS cors error, while API route remains unaffected

In my Next.js application, I have encountered an issue where executing a call to fetch a page from an external website works perfectly fine when done from the backend through an API route. However, when attempting the same action from the frontend, I encou ...

Setting a default action for an Ext.Ajax.request error situation

In my application, I frequently make ajax requests using the Ext.Ajax.request method. Often, I find myself skipping error handling for failed requests due to time constraints or lack of interest in implementing fancy error handling. As a result, my code us ...

I'm experiencing an issue with fullCalendar where the dayRender function is not functioning as expected

I have been using fullCalendar and I am looking to customize the color of specific days. I have successfully created an overlay that is displayed when a user clicks on a particular day. Everything works as expected with the overlay, but now I am encounte ...

The placeholder within my input moves up and down when switching the input type from password to text

Currently, I am encountering an issue with the styling of a standard input element in React. Specifically, the placeholder text moves up and down by about 2px when viewed on Chrome, while there are no problems on Safari. How can I go about resolving this i ...

How can you apply filtering to a table using jQuery or AngularJS?

I am looking to implement a filtering system for my table. The table structure is as follows: name | date | agencyID test 2016-03-17 91282774 test 2016-03-18 27496321 My goal is to have a dropdown menu containing all the &apo ...

Are there any customizable actions available for the `yarn remove [package]` command, such as post-installation hooks?

I must execute a script following the completion of the following commands: yarn add [package] yarn remove [package] yarn upgrade [package] yarn install postinstall gets triggered after yarn add, yarn upgrade, and yarn install. However, it doesn't s ...

How can I execute a task following a callback function in node.js?

Is there a way to run console.log only after the callback function has finished executing? var convertFile = require('convert-file'); var source, options; source = 'Document.pdf'; options = '-f pdf -t txt -o ./Text.txt'; ca ...

Encountering difficulties when attempting to upload to Google Cloud using a signed URL

Seeking help to troubleshoot why the video upload is not working as expected. I am able to successfully connect to my bucket using a signedURL, but when trying to upload the video, it's not functioning properly. const submitVideo = async () => { ...

Webpack creating a bundle file with no content

I'm currently facing a challenge with webpack/webpack-stream while trying to bundle some JavaScript files. The issue I am encountering is that, despite generating the bundle.js file, it turns out to be empty. To ensure clarity, I've provided the ...

How can Backbone.js transfer data between different views?

Here, I am facing a challenge where I have two views and I need to transfer data from one view to the next, but I'm unsure about how to go about implementing this. Let's start with the first function view: var CategoriesView = Backbone.View.ext ...

Tips on getting the Jquery .load() function to trigger just once and executing an Ajax request only once

Upon loading the page, I am utilizing the JQuery .load() function to retrieve content from a PHP file. The content loads successfully but it keeps reloading continuously as observed through Chrome Developer tools. I only want the content to load once. var ...

Utilize Recurly's Node to generate a transaction with stored billing details

I need help creating a transaction using Recurly stored billing information. I am currently using the node-recurly module in my Node.js application. https://github.com/robrighter/node-recurly Below is the code snippet that I have written: recurly.transa ...

Ways to determine if the keys of an object are present in an array, filtered by the array key

Working on an Angular 2 Ionic application and I'm wondering if there's a straightforward way to filter individuals by age in a specific array and then verify if any key in another object matches the name of a person in the array, returning a bool ...

Is there a way to prevent the letters from moving when I hover over them?

What occurs when the numbers are hovered over: https://gyazo.com/20b6426d435551c5ee238241d3f96b4d Whenever I hover over the pagination numbers, they shift to the right, and I am unsure of what mistake I made in my code that's causing this. Below, I ...