Utilize Material-UI to display data retrieved from axios (image may not be visible)

An issue with the display of my code image has arisen. Interestingly, the Axios calls work effectively when I console them.

import { Container, Grid, Paper } from '@mui/material';
import { useEffect, useState } from 'react';
import { styled } from '@mui/material/styles';
import ButtonBase from '@mui/material/ButtonBase';
import axios from 'axios';


const Img = styled('img')({
  margin: 'auto',
  display: 'block',
  maxWidth: '100%',
  maxHeight: '100%',
});

const Home = () => {

  const [albums, setAlbums] = useState([]);

  useEffect(async () => {
    const res = await axios.get(`https://jsonplaceholder.typicode.com/albums?userId=2`);

    let tempArr = JSON.parse(JSON.stringify(res)).data;
    let photos = [];

    tempArr.forEach(async (element, index) => {
      let res2 = await axios.get(`https://jsonplaceholder.typicode.com/albums/${element.id}/photos`);
      photos = JSON.parse(JSON.stringify(res2)).data;
      element.photos = photos;
      tempArr[index] = element;
    });

    setAlbums(tempArr);
  }, []);

  return (
    <div>
      <Container sx={{ marginTop: '10px;' }}>
        <Grid container spacing={2}>
          {albums.map((item, key) => {
            return (
              <Grid key={key} item sm={6} xs={12}>
                <Paper sm={{ textAlign: 'center' }} sx={{ p: 2, margin: 'auto', flexGrow: 1 }}>
                  <Grid container spacing={2}>
                    <Grid item>
                      {(undefined !== item['photos'] && item['photos'].length) &&
                        <ButtonBase sx={{ width: 128, height: 128 }}>
                          <Img alt="complex" src={item['photos'][0]['thumbnailUrl']} />
                        </ButtonBase>
                      }
                    </Grid>
                  </Grid>
                </Paper>
              </Grid>
            )
          })}
        </Grid>
      </Container>
    </div>
  )
}

export default Home;

If someone could investigate this, it would be greatly appreciated. The array structure after setAlbums(tempArr); looks like this:

[
    {
        "userId": 2,
        "id": 11,
        "title": "quam nostrum impedit mollitia quod et dolor",
        "photos": [
            {
                "albumId": 11,
                "id": 501,
                "title": "asperiores exercitationem voluptates qui amet quae necessitatibus facere",
                "url": "https://via.placeholder.com/600/cda4c0",
                "thumbnailUrl": "https://via.placeholder.com/150/cda4c0"
            },
            {
                "albumId": 11,
                "id": 502,
                "title": "omnis qui sit et",
                "url": "https://via.placeholder.com/600/74e371",
                "thumbnailUrl": "https://via.placeholder.com/150/74e371"
            },
            {
                "albumId": 11,
                "id": 503,
                "title": "modi voluptas fugiat eos",
                "url": "https://via.placeholder.com/600/9022fb",
                "thumbnailUrl": "https://via.placeholder.com/150/9022fb"
            },
            
        ]
    }
]

However, attempting to loop through

<p>{item['photos'][0]['thumbnailUrl']}</p>
results in an error:

TypeError: Cannot read properties of undefined (reading '0')

Answer №1

Referencing this insightful response and this particular concern, an adjustment can be made to the useEffect function as shown below:

useEffect( () => {
    const fetchAlbums = async () => {
      const res = await axios.get(`https://jsonplaceholder.typicode.com/albums?userId=2`);

      const tempArr = JSON.parse(JSON.stringify(res)).data;
      const tempAlbums = await Promise.all(tempArr.map(async (element) => {
        const res2 = await axios.get(`https://jsonplaceholder.typicode.com/albums/${element.id}/photos`);
        const photos = JSON.parse(JSON.stringify(res2)).data;
        return { ...element, photos };
      }));
      setAlbums(tempAlbums);
    }
    fetchAlbums();
  }, []);

Furthermore, you can update the way Img is implemented to handle the issue of missing photos:

<Img alt="complex" src={item.photos?.[0].thumbnailUrl || "<path to placeholder when the album has no photos>"} />

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

The native styled component does not function properly with Material-UI media query

Is it feasible to utilize [props => props.theme.breakpoints.up('sm')] in this context? import React from 'react'; import { styled, withTheme } from '@material-ui/core'; export const DefaultContent = withTheme( styled(({ th ...

Error in MUI: Unable to access undefined properties (reading 'drawer')

Recently, I encountered an unexpected error in my project using MUI v5.0.2. Everything was working fine just a week ago with no errors, but now I'm facing this issue without any changes made to the code: Error: TypeError: Cannot read properties of un ...

Clicking the button becomes impossible after entering text and using `evaluateJavascript`

I am currently working on finding a solution to input the receipt number and click the 'Check Status' button on this specific website: After successfully entering the receipt number: document.getElementById('receipt_number').value = &a ...

Autofill Text Input with React Material-UI

For my current project, I am utilizing Material UI and React. Each TextField in the project has a button next to it, and when the button is clicked, I want it to retrieve the value of its corresponding TextField and set that value as the input for another ...

The Redux Toolkit Slice Reducer fails to function properly when incorporating an extra Reducer that is not compatible

I am relatively new to the world of Redux and have been attempting to use RTK right from the start. It has been quite a challenging and confusing experience for me so far. Recently, I decided to include a standard Reducer instead of an extraReducer in my ...

Unable to transfer an array from getStaticProps method in Next.js

Whenever I pass a JSON array from getStaticProps in Next.js, I encounter this specific error message when trying to access it. TypeError: Cannot read property 'contentBody' of undefined module.exports../pages/[author]/[article].js.__webpack_expo ...

Is it possible for three.js to integrate information from REST APIs?

Currently, I am in the process of learning three.js and have successfully created basic 3D models using hardcoded values. My goal now is to retrieve these values from a database that I have set up in MSSQL Server. These x, y, and z parameters are stored ...

Combine es6 imports from the identical module using an Eslint rule or plugin

Looking to consolidate my ES6 imports from a single module into one for my React project. For example: import { Title } from "@mantine/core"; import { Center } from "@mantine/core"; import { Divider } from "@mantine/core"; T ...

Experience the dynamic synergy of React and typescript combined, harnessing

I am currently utilizing ReactJS with TypeScript. I have been attempting to incorporate a CDN script inside one of my components. Both index.html and .tsx component // .tsx file const handleScript = () => { // There seems to be an issue as the pr ...

Tips for customizing the appearance of a Material UI Accordion: adjusting divider lines and collapse icons

I have set out to design a unique Material UI accordion that resembles this image: https://i.stack.imgur.com/ZWzCq.png My attempt at creating this customized MUI accordion involves the following code structure (this accordion also integrates custom search ...

What is the best way to prevent duplicate calls in my basic search function?

Seeking a solution for handling API calls outside of the React component, I have implemented a basic search by title query using a public API. Check out my code on CodeSandbox. import * as React from "react"; import axios from "axios"; ...

Creating a File Download button in Next.js without receiving a "window is not defined" error

React components don't recognize 'window' or 'document' objects until the component is mounted. I'm working on creating a download button that will receive an Excel file processed by the backend server. In my previous non-Rea ...

When I execute `npm install`, what does the error message `npm ERR! ERESOLVE could not resolve` indicate?

My current version of node.js is 18.12.0 and npm is at 8.19.2. When I attempt to run npm install, an error is displayed: https://i.stack.imgur.com/uppdj.png I am able to bypass the error by using --force, but this leads to a dependency tree issue. ...

What steps can I take to ensure my React js Material-UI table is both responsive and evenly spaced?

Currently utilizing the MaterialTable component sourced from material-ui, I've encountered two issues that require resolution. 1. Is there a way to ensure equal spacing of columns? Currently, there seems to be an unnecessary amount of space between t ...

Interacting with various Node.js APIs from a React frontend

Hey there! I'm currently working on a project that utilizes Node.js (Typescript) for the backend and React with Express for the frontend. The backend consists of 3 docker containers, each assigned to different ports - 1 for Postgres, 2 for ServiceA, ...

Navigating screen orientation changes in ReactJS

Currently, I am working on a component that needs to update its content based on the screen orientation (portrait/landscape). Here is my approach: var Message = React.createClass({ getInitialState: function() { return {isPortrait: true} } ...

Rollup and React are having trouble compiling JSX code

While attempting to incorporate Rollup with React, I've come across an issue when Rollup encounters JSX. Unexpected token... export default () => <p>M... I've created a repository that triggers this error. Most of the documentation and ...

Invoke a function on React whenever the context is updated

Within my functional component, I have a scenario where it returns another function: function Lobby() { const user_context = useContext(UserContext) return ( <div>{renderData(user_context.state.data)}</div> ) } export default L ...

Ways to prevent the component from rendering until the ajax call has finished in reactjs

I am working on a project with a parent component and child component. The parent component contains a form where users input their name and phone number, and upon pressing submit, I want these values to be passed as props to the child component. The chi ...

The default value for the MUI object in the Select component is not displayed initially, but is shown once

Is there a way to set a default value for the dropdown in this code snippet? Currently, the "chosenValue" is set by default, but I need to change it so that something else appears selected when the page loads. How can I achieve this? You can refer to thi ...