React is not updating the UI after receiveing data from the API call (using hooks)

Viewed 47
const [data, setData] = useState(null);

  useEffect(() => {
    const getData = async () => {
    await fetch('http://localhost:4000/data')
    .then(res => res.json())
    .then(fetchedData => { 
      setData(fetchedData); 
      console.log(fetchedData) 
    })}
    getData();
  }, [])

  return (
    <div className="App">
      <Header />    
      <ul>{ data &&
        data.map((item, index) => {
          item.map(object => {
            Object.keys(object).map((key) => 
               (<li key={index}>{object[key]}</li>)
            );
          })
        })}</ul>
    </div>

the data structure is like this: [[{'sum': 210}], [{'total': 210}], [{'free': 210}], [{'discounted': 210}]]

When I log the data in the console I see it but I see nothing in the UI just <ul></ul>

1 Answers

You're not returning anything from the arrow functions that you pass to .map(..). Either add a return statement or get rid of the surrounding curly brackets

data.map((item, index) => 
  item.map(object => 
    Object.keys(object).map((key) => 
      (<li key={index}>{object[key]}</li>)
    )
  )
)

OR

data.map((item, index) => {
  return item.map(object => {
    return Object.keys(object).map((key) => 
      (<li key={index}>{object[key]}</li>)
     );
  })
})
Related