ReactJS not rendering Axios GET request component

I am facing an issue with displaying my components on the screen after completing a promise. I am utilizing the imgur API to make requests, and although the request works fine and data is received back from the API, when I update the state in my component and pass it as props, no data is displayed.

Below is my main component named app.js

import React, {Component} from 'react';
import axios from 'axios';
import ImageList from './image_list';

export default class App extends Component {
    constructor(props) {
        super(props);
        this.state = {images: []};
    }

    componentWillMount() {
        // Retrieving an array of 60 objects from IMGUR_URL.
        axios.get(IMGUR_URL).then(res => this.setState({images: res.data.data}));
    }

    render() {
        return (
            <div>
                {/* Passing the images state */}
                <ImageList images={this.state.images} />
            </div>
        );
    }
}

I have seen some examples using the componentDidMount function, but they did not bring any changes to my application.

Here are my two child components: The value of props is obtained from the ImageList component.

image_detail.js

import React, {Component} from 'react';

export default class ImageDetail extends Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (
            <div>
                <li>
                    <img src={this.props.image.images[0].link} alt={this.props.image.title} />
                </li>
            </div>
        );
    }
}

The values of props are coming from App.js through the axios GET request. So, I am uncertain about what I might be overlooking here.

image_list.js

import React, {Component} from 'react';
import ImageDetail from './image_detail';

export default class ImageList extends Component {
    constructor(props) {
        super(props);

        this.RenderedImages = this.props.images.map(image => <ImageDetail key={image.id} image={image} />);
    }

    render() {
        return (
            <div>
                <ul> {this.RenderedImages} </ul>
            </div>
        );
    }
} 

Additionally, I am unsure about what should be included inside the constructor method.

Answer №1

Another question that arises is, what should be included in the constructor method?

In general, state initialization is recommended to be placed within the constructor.

For the ImageList component, my suggestion would be to move the RenderedImages into the render function as shown below:

import React, {Component} from 'react';
import ImageDetail from './image_detail';

export default class ImageList extends Component {
    constructor(props) {
        super(props);
    }

    render() {
        return (
            <div>
                <ul> {this.props.images.map(image => <ImageDetail key={image.id} image={image} />)} </ul>
            </div>
        );
    }
} 

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

Utilizing Material UI Text Field to Restrict Length and Data Type with react-hook-form

Struggling with managing user input in the code snippet provided. I can't seem to restrict the number of digits a user can enter into a text field while also controlling the type of input. If I remove type: "number", then I am able to contr ...

Having trouble importing Material UI and working with ClickAwayListener

For my current project, I am utilizing material-ui to implement the functionality for changing passwords. In this root file, I am importing several child components: Personalize.js import React, { useContext, useState } from 'react'; import Cook ...

Utilize AWS Code Pipeline to deploy a React application with customizable build variables

Currently, I am in the process of deploying a create-react-app as a static site on AWS S3 with CodePipeline managing the build. Within our codebase, we have REACT_APP_**** variables that are injected during the build process. My concern is how to inject d ...

The call to the hook is invalid. In order to use hooks, they must be called within the body of a function component in

So, in my upcoming application, I am incorporating the react-google-one-tap-login library which features the useGoogleOneTapLogin hooks that need to be invoked within a React component. However, when I attempt to use it in this manner: func() { useGoogle ...

How can we style the <a> link once it has been downloaded?

Is there a way to change the color of a download link after it has been clicked on? I've attempted using the visited attribute, but it only seems to work with regular links and not with download documents: Appreciate any help ...

React Native is facing difficulty in fetching pagination data which is causing rendering errors

Currently, I am working on fetching pagination data from an API. The process involves retrieving data from https://myapi/?page=1, then from https://myapi/?page=2, and so on. However, despite following this logic, I encountered an error that has left me puz ...

Open the overflow div within a table data cell

My goal is to create a drag-and-drop schedule tool similar to Fullcalendar. I have decided to use a table layout with a rectangular div inside each TD cell to represent tasks. <table onDragEnd={dragend}> <tr> <th>0</th> ...

What could be the reason for the handleOpen and handleClose functions not functioning as expected?

I am facing an issue with my React component, FlightAuto, which contains a dropdown menu. The functionality I'm trying to achieve is for the dropdown menu to open when the user focuses on an input field and close when they click outside the menu. Howe ...

Exploring ways to expand the theme.mixins feature in MUI 5

Currently, I am in the process of updating Material UI from version 4 to 5 and encountering challenges with my existing theming. Since we are using typescript, it is important to include the appropriate types when extending themes. I intend to include th ...

What is the best way to eliminate the [lang tag] from a URL in Next.js?

I am looking to eliminate either the /en or the /it from the URL without explicitly adding it. i18next seems to be doing it automatically, and I am unsure how to disable this behavior. I simply want it to happen in the background. https://i.stack.imgur.co ...

Unusual problem encountered with the MUI/Material UI multiselect feature

Looking for a solution: check out this codesandbox multiselect demo Currently trying to extract unique items from an array based on id in order to display them as options. Utilizing the MUI Select component. Successfully creating distinct arrays using di ...

Exploring the capabilities of combining Typescript with withStyles in the latest @material-ui/core framework

I have been working on updating some old Typescript code that was using material-ui@next to now use @material-ui/core. Typescript Version: 2.8.3 @material-ui/core: 1.1.0 I created a simple component that accepts a single prop, but when I try to use it, t ...

`Balance in structure`

Having trouble with CSS. I would like to make this form symmetrical. Buttons should be in one column, textfields in another, and the question mark should also have its own column. Apologies if the ticket structure is not perfect, this is only my second on ...

Display a list of items using ReactJS by mapping through an array of objects and rendering based on

How can I render a set of <div> </div> based on the items in an object without having to specify their names? In the code snippet below, I want the display of WorkObjectID and WorkObjectVal to be dynamic rather than static. If I include TempOb ...

In Reactjs, you can prevent users from selecting future dates and times by modifying the KeyboardDateTimePicker component

I am currently using the Material UI KeyboardDateTimePicker component and have successfully disabled future dates with the disabledFuture parameter. However, I am now looking for a way to disable future times as well. Any suggestions or solutions would b ...

Is it possible to enable the Button ripple effect selectively in Material-UI?

To disable all ripples, I can add the following code to the theme object: components: { MuiButtonBase: { defaultProps: { disableRipple: true, }, }, }, If I only want to disable ripples for everything except IconButtons, I can use this co ...

Customizing the underlineFocusStyle of a material-ui TextField component using regular CSS styling

When working with Material-UI components, you have the option to provide a style object for the component itself within the JSX tag. However, in certain cases like the underlineFocusStyle of a TextField component, you need to use a separate style object. ...

Is there a way to execute an Apollo GraphQL query prior to the initial rendering of the App component? (while also relying on it)

How can I effectively call an Apollo query in my App component, where the component's behavior depends on the result? My goal is to redirect users to different pages based on their privileges. I'm struggling with figuring out the right way an ...

Triggering event within the componentDidUpdate lifecycle method

Here is the code snippet that I am working with: handleValidate = (value: string, e: React.ChangeEvent<HTMLTextAreaElement>) => { const { onValueChange } = this.props; const errorMessage = this.validateJsonSchema(value); if (errorMessage == null ...

Unable to display information retrieved from an API within a React application

I am facing an issue with rendering questions fetched from an API. I have set up the state and used useEffect to make the API call. However, when I try to display the questions, it seems to disrupt my CSS and show a blank page. I even attempted moving the ...