Rendering JSON responses in React.js can be achieved using either the fetch function or axios library

I've spent way too much time struggling and I can't seem to concentrate anymore.

My goal is simple - I just want to fetch JSON data from a URL and display it visually in the browser. It doesn't even have to be formatted, at least not until I overcome this obstacle.

Although I managed to get it to appear in the console using console.log, I'm struggling to pass the response to the render method. I've simplified the code below to try and at least see something on the webpage.

import React, { Component } from 'react';

var co = require('co');

co(function *() {
  var res = yield fetch('https://api.stackexchange.com/2.2/search?order=desc&sort=activity&intitle=perl&site=stackoverflow');
  var json = yield res.json();
  console.log(res);
});

class App extends Component {

render() {
return (
   <div className="App">
     INSERT JSON HERE
   </div>
);
}
}

export default App;

I also managed to retrieve the response using:


fetch('https://api.stackexchange.com/2.2/search?order=desc&sort=activity&intitle=perl&site=stackoverflow')
.then(function(res) {
    return res.json();
}).then(function(json) {
    console.log(json);
});

Initially, I opted to use axios because my initial thought was "oh well, I'll use axios because who's awesome? I'm awesome."


axios.get('https://api.stackexchange.com/2.2/search?order=desc&sort=activity&intitle=perl&site=stackoverflow')
.then(function(response) {
console.log(response.data);
});

However, that turned out to be wrong as today, I am far from feeling awesome.

I would appreciate any help I can get! In my original plans, I intended to use map to iterate over the "items", so additional points if you can guide me closer to success in that aspect.

Answer №1

import React, { Component } from "react";
import axios from "axios";

const API_URL = "https://api.stackexchange.com/2.2/search?order=desc&sort=activity&intitle=perl&site=stackoverflow";

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

  componentDidMount() {
    var _this = this;
    axios.get(API_URL)
    .then(function(response){
      _this.setState({
        items: response.data.items
      });
    })
    .catch(function(error) {
      console.log("ERROR ", error);
    })
  }

  render() {
    const displayItems = this.state.items.map(function(element, index) {
      return <li key={index}>{element.title}</li>
    });

    return (
      <ul className="App">
        {displayItems}
      </ul>
    );
  }
}

Answer №2

To achieve this, React's Component State and Lifecycle can be utilized.

For more information, refer to: React State/Lifecycle

The Fetch call can be placed in the componentDidMount function of the component, with the callback setting the state for viewing.

If Fetch is used, the component structure might resemble the following:

class App extends Component {
 constructor(props) {
  super(props);
  this.state = {
   data: false
  };
  this.receiveData = this.receiveData.bind(this);
 }
 componentDidMount() {
  var _self = this;
  fetch('https://api.stackexchange.com/2.2/search?order=desc&sort=activity&intitle=perl&site=stackoverflow')
  .then(function(res) {
     return res.json();
  }).then(function(json) {
     console.log(json);
     _self.receiveData(json);
  });
 }
 receiveData(data) {
  this.setState({data});
 }
 render() {
  return <div>{this.state.data}</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 aria-role in Material UI's <Icon> component for enhanced accessibility

I've been using Material UI's <Icon /> component and came across a reference in their documentation about being able to use role="img", which is mentioned here: https://material-ui.com/components/icons/#semantic-svg-icons. However ...

Include new item in current JSON data using Java

I am facing a challenge in adding a new JSON object to "carTypes" inside the cars.json file. Can anyone guide me on how to achieve this? I can retrieve data from cars.json but do not know the process of adding data to it. The current content of my cars.j ...

Developing a personalized collection of top picks and syncing them across multiple

Currently, I am in the process of developing a favorites list using a custom listview. ----------------------------------- <Item_Name> <favorite button> ----------------------------------- On the listView, there is an onItemClickListener. ...

Divide material-ui toolbar into separate left and right sections

Is there a way to split the material-ui toolbar into a left and right part? I want to display the numSelected on the left side of the toolbar, and the delete button and edit button on the right side. Currently, my output shows these buttons just beside t ...

Best practice for executing two .save() operations in mongoose

I've been attempting to save to two different documents and models within the same function, but I keep encountering strange errors no matter what approach I take. It appears that for some reason, mongoose is not allowing this to work as intended. Cu ...

When refreshing, the React state object is mysteriously transforming into "[object Object]" while utilizing sessionStorage

Currently, I am working on a practice fullstack ecommerce application using Postgres, Express, and React as part of my fullstack course. My inquiry pertains specifically to React. Upon logging into the application, I can successfully manage a cart in the ...

Can you please explain how to indicate a modification in a JSON object with Polymer, transferring information from Javascript, and subsequently displaying child elements?

Currently, I am creating a JSON file that contains a random assortment of X's and O's. My goal is to display these elements in a grid format using a custom Polymer element. Initially, everything works fine as I can see a new grid generated each t ...

Tips on enhancing the appearance of your numberbox with vibrant colors

Hello everyone! I am working with some devextreme code blocks and need help in changing the border color of a numberbox to red. Can anyone guide me on how to achieve this? import React, { useState } from 'react'; import { NumberBox } from 'd ...

Converting NSString to a JSON formatted string

My current situation involves an NSString that is not a valid JSON string. I need to convert it into a JSON string and save it into an NSArray. Here is the content of my NSString: [, {"Agent":" Visitor", "Time":"03:18 AM", "Message":"Msg from : file:///Us ...

Learn how to efficiently reload a card in React upon submitting new data

Is there a way to automatically refresh the card component after submitting data without having to manually refresh the page? I've tried using useEffect but it's not updating the data even though the value is changing. Any suggestions on how to r ...

Remove a record from a SQL database using a React front-end application

I'm facing an issue with deleting a row from an SQL table using input from a React front end. I had previously succeeded in this task, but after updating the columns in the table, I am struggling to replicate the delete operation. It seems like my req ...

Synchronous fetch request within Core Data

In my application, I am utilizing Alamofire to fetch JSON data asynchronously from a server. In order to achieve this, I have the following objectives: 1. Execute multiple fetch requests and retrieve JSON data 2. Send the JSON data to my DataImporter ...

Encountered a TypeError when trying to access the 'subroute' property of an undefined object during JEST and enzyme testing

Currently, I'm utilizing jest along with the enzyme library for testing React components using the create-react-app boilerplate. After running the test suite, I encountered the following error: I haven't been able to find a solution to this issu ...

Executing the event handler only once

In my React project, I have a button that toggles a boolean state. However, I realized that the button can both set and unset the state due to its toggle functionality. I only want the state to be changed once. Is there a different function I can use ins ...

The error message "Invalid JSON payload. Root element needs to be a message" is returned when using the Google Sheets API with python 2.7

I have been struggling with an error for several weeks now and have attempted solutions from previously asked questions regarding the Python API for Google Sheets. Every time I make a "write" request to my spreadsheet using the Google Sheets API for Pytho ...

How can I enable the right click function to close a Modal in Material-UI?

Is there a way to close a Menu (or more specifically, a Popover) with a right click or any mousedown event? I came across the documentation that discusses this: https://material-ui.com/components/menus/#MenuListComposition.js After some cleanup, I was ab ...

ReactJS: The input is not triggering the onChange event

Take a look at this code snippet: import React, { Component, useImperativeHandle } from 'react'; class SearchBar extends Component { render() { return <input onChange={this.onInputChange} />; } onInputChange(event) { console.log(event) } ...

Guide to establishing a connection to CloudantDB through spark-scala and extracting JSON documents as a dataframe

I have been attempting to establish a connection with Cloudant using Spark and read the JSON documents as a dataframe. However, I am encountering difficulties in setting up the connection. I've tested the code below but it seems like the connection p ...

Having trouble getting the Popover to show up in the right spot within the Dialog

I'm facing an issue with a Dialog and a ListItem where clicking on the item should trigger edit mode by displaying a Popover. The setup worked fine in an older version of MUI using a Modal, but upon updating to the latest version, the functionality br ...

When using CSS @media print with inches, different dimensions are displayed post-printing

I'm currently working on a project that involves printing a single div from my webpage. However, I've encountered some issues with the @page tag not affecting the print output as expected. I attempted to manually set the dimensions of the element ...