Home > Blockchain >  React: Cant render simple JSON from API call
React: Cant render simple JSON from API call

Time:07-14

I'm able to log the response in console, but for some reason it cant return it to my page. Any pointers help...Thanks so much

import React, { useState, useEffect, Component } from 'react';

function Home(){
  const [data, setData] = useState([]);

  const getData= ()=>{
    fetch('http://localhost:8070/foo')
    .then(function(response){
      console.log(response)
      return response.json();
    })
    .then(function(myJson){
      console.log(myJson);
    })
  }
  useEffect(()=>{
    getData()
  },[])


  return (
    <div className="Home">
      {
        data && data.length >0 && data.map((items)=><p>items.cost_center_code</p>)
      }
    </div>
    )
}


export default Home;

CodePudding user response:

You're not doing anything with the response in the code you gave, you need to set your data state after you get the response.

const getData= ()=>{
    fetch('http://localhost:8070/foo')
    .then(function(response){
      console.log(response)
      return response.json();
    })
    .then(function(myJson){
      console.log(myJson);
      setData(myJson) // <-- important line here
    })
  }

I'd recommend reading the tutorial on useState

CodePudding user response:

You are not calling setData anywhere, so data is always []. You need to call setData after you get your json from api

  • Related