DaveDavidson DaveDavidson - 2 months ago 47
React JSX Question

React output JSON from API

I have managed to get JSON from my api I have created, however I am having trouble actually rendering that JSON. I have managed to output it in the console by 'stringify'-ing it, however I cannot seem to actually render JSON to the page.

import React, { Component } from 'react';
import './App.css';
import $ from 'jquery';

function getData() {
return $.ajax({
type: "GET",
url: 'http://localhost:3001/data',
data: {},
xhrFields: {
withCredentials: false
},
crossDomain: true,
dataType: 'json',
success: handleData
});
}
function handleData(data /* , textStatus, jqXHR */ ) {
console.log(JSON.stringify(data));
return JSON.stringify(data);
}

class App extends Component {
render() {
return (
<div className="App">
<header>
<h2>Last Application Deployment </h2>
</header>
<div id='renderhere'>
{JSON.stringify(getData().done(handleData))}
</div>
</div>
);
}
}

export default App;

Answer

you cant execute a function in render method in return.you can use react lifecycles and store result in state like this =>

class App extends Component {

      state = {result : null}          

      componentDidMount = ()=>{

        $.ajax({
           type: "GET",
           url: 'http://localhost:3001/data',
           data: {},
           xhrFields: {
             withCredentials: false
           },
           crossDomain: true,
           dataType: 'json',
           success: (result)=>{
              this.setState({result : result}); 
           }
         });

      };

      render() {
        return (
          <div className="App">
            <header>
              <h2>Last Application Deployment </h2>
            </header>
            <div id='renderhere'>
              {this.state.result && and what you want because i dont                                  know why you want use JSON.stringfy - you use .map() or ...}
            </div>
          </div>
        );
      }
    }

I suggest you see this article and this.