Solo tengo una función que primero obtiene la lista de dispositivos. la lista es una matriz JSON. luego, la función recorre cada elemento y solicita la sombra.
La función crea una nueva matriz utilizando las propiedades del dispositivo y la propiedad de la sombra.
La página REACT renderiza y muestra los datos por un segundo y luego desaparece.
Si modifico la función getShadow para que solo devuelva la lista de dispositivos (sin sombras), la página se muestra bien. Pero el problema comienza cuando construyo la nueva matriz utilizando los datos ocultos de cada dispositivo.
¿Alguna idea de lo que me estoy perdiendo aquí?
muchas gracias
aquí está el código
async function getShadows() { const listThings_command = new ListThingsCommand({}); const data = await iotClient.send(listThings_command); /* First get the list of things */ const things = data.things; let devices_list = []; // to store the final array with data to render let shadowRequests = things.map (thing => { /* List calls to get shadow for each thing */ return new Promise((resolve, reject) => { const getThingShadow_command = new GetThingShadowCommand({thingName: thing.thingName}); /** get device shadow */ iotDataPlaneClient.send(getThingShadow_command).then( (data) => { const string_data = new TextDecoder('utf-8').decode(data.payload); /* Decode payload as it is returned in Uint8Array format*/ const shadow_data = JSON.parse(string_data); var deviceInfo = { /* Create a new object to store required device info*/ thingName : thing.thingName, thingTypeName: thing.thingTypeName, thingArn : thing.thingArn, shadow : shadow_data.state.reported }; resolve(deviceInfo); }, (error) => { reject(error); } ); }) }) Promise.all(shadowRequests).then((data) => { data.forEach (res => { /* loop over each promise */ if (res) { devices_list.push(res); /* add the data as a new element in the array*/ } }) } ) return devices_list; }; function Home (){ const [mydevices, updateMydevices] = React.useState([]); useEffect(() => { getShadows().then(data => updateMydevices(data)); }, []); return ( <div className="App"> <h1>Dashboard</h1> <div> <h4>Devices List</h4> <ListGroup id="device_list"> { mydevices.map((device, key) => { return ( <ListGroup.Item key = {key}> <div>{device.thingName} </div> </ListGroup.Item> ) }) } </ListGroup> </div> </div> ); } ```Si no usa esperar aquí, la lista de dispositivos se devolverá antes de que se completen las solicitudes de duplicación. Entonces siempre será una matriz vacía. Puedes probar algo como esto.
try { const data = await Promise.all(shadowRequests); data.forEach (res => { /* loop over each promise */ if (res) { devices_list.push(res); /* add the data as a new element in the array*/ } }) } catch(err) { //handle error } return devices_list;