Search code examples
jsonreactjsfetchaxiosco

React.js render json response, co fetch or axios


I've been pulling my hair out too long and I can't focus anymore.

I am trying to take the json from a url and just render it visually in the browser. It doesn't even need to be formatted, at least it doesn't until I get past this hurdle.

I can get it to show up in the console via console.log, but I can't seem to get the response into the render method. I've simplified it down to the code below until I can see something on the page.

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

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 have also retrieved 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);
    });

I originally started by using axios because I thought "oh man, I'm going to 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);
  });

but that was a fallacious because today I am not awesome.

I'll take whatever help I can get! My original plans also included using map to just iterate over the "items" so extra points if you can steer me closer to salvation in that area.


Solution

  • import React, { Component } from "react";
    import axios from "axios";
    
    const 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(URL)
        .then(function(res){
          _this.setState({
            items: res.data.items
          });
        })
        .catch(function(e) {
          console.log("ERROR ", e);
        })
      }
    
      render() {
        const renderItems = this.state.items.map(function(item, i) {
          return <li key={i}>{item.title}</li>
        });
    
        return (
          <ul className="App">
            {renderItems}
          </ul>
        );
      }
    }