I'm trying to render an object for each entry in a database, and attach text such as a URL, title, and description to each object depending on their relative database entries.
So far I have a cube for each entry in DB showing in the scene, however the data is logging as undefined. From what I can see, my code should be working but it is really really 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)
}
}
Above is the code to fetch each entry in my MongoDB collection (it's a list of file paths and data such as file title, description, and labels).
From examples I've found, 'userData' seems to be the way to go.
Currently I can hover over the objects and they change color with Raycasting. In future once I get past this obstacle I will create a way to see the text data such as title when the object is hovered over, and lead to the URL when clicked.
I'm new to three.js and it baffles me.
I think you're confusing the structure of data. Sometimes you treat is as an object, and sometimes you treat it as an array.
For example, if you're using data.length in your for() loop, then data is an array. You can't access .description or .title of an array, but maybe you can access them inside each element inside the array with: data[0].description, data[1].description, etc...
// Create variable to make a reference
// to the current element while looping in the array
var arrayElement;
for (var i = 0; i < data.length; i++) {
// Get the element for this iteration
arrayElement = data[i];
cube = new THREE.Mesh(geometry, material.clone());
// Now you can acces the information in 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)
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With