Reputation: 7145
import React, { useEffect, useState } from "react";
import "./styles.css";
export default function App() {
const [videoDevicesList, setVideoDevices] = useState([]);
useEffect(() => {
// navigator.mediaDevices.enumerateDevices().then(gotDevices)
if (true) {
(async () => {
const devices = await navigator.mediaDevices.enumerateDevices();
const videoInput = devices.filter(
(device) => device.kind === "videoinput"
);
setVideoDevices(videoInput);
})();
}
}, []);
return (
<div className="App">
{JSON.stringify(videoDevicesList)}
<h1>Loop</h1>
{videoDevicesList.forEach((device) => (
<div key={device.groupId}>{device.groupId}</div>
))}
</div>
);
}
I have this code. {JSON.stringify(videoDevicesList)}
prints an array
in the UI.
Also typeof videoDevicesList
retruns object
.
And I want to loop through the array
and print the groupId
.
But this doesn't work.
How do I fix this error?
Any help!
Thanks in advance. =)
Upvotes: 1
Views: 228
Reputation: 71
maybe you can try this way
import React, { useEffect, useState, useMemo } from "react";
import "./styles.css";
export default function App() {
const [videoDevicesList, setVideoDevices] = useState([]);
useEffect(() => {
// navigator.mediaDevices.enumerateDevices().then(gotDevices)
if (true) {
(async () => {
const devices = await navigator.mediaDevices.enumerateDevices();
const videoInput = devices.filter(
(device) => device.kind === "videoinput"
);
setVideoDevices(videoInput);
})();
}
}, []);
const groupIds = useMemo(() => {
let $groupIds = [];
videoDevicesList.forEach((device) =>{
$groupIds.push (
<div key={`${device.groupId}`}>{device.groupId}</div>
)
} )
return $groupIds
},[videoDevicesList])
return (
<div className="App">
{JSON.stringify(videoDevicesList)}
{typeof videoDevicesList}
<h1>Loop</h1>
{groupIds}
</div>
);
Upvotes: 1
Reputation: 9571
change your forEach
to map
map
returns a new array, in this case its an array of components
forEach
simply iterates over each item, it doesn't return anything.
https://codesandbox.io/s/epic-keldysh-u9x8i
Upvotes: 2