1
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. =)

Code sand box

1

2 Answers 2

2

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

Sign up to request clarification or add additional context in comments.

Comments

1

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>
  );

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.