Home > Blockchain >  Unable to render any data on the web page
Unable to render any data on the web page

Time:10-17

I'm quite new to React and typescript, trying to build simple application which extracts data from API and displays it on web page. After reading some article on the internet and playing around with the code I have managed to fix the errors. But now I'm unable to display any data on the web page. I don't see any errors and I see the data in the console log.

I'm unable to understand why am I getting empty array in the return logic. Can someone advice.

Code App.tsx

import { useEffect, useState } from 'react';
import './App.css';
import ApiProps ,{ DataApiResponse }from '../src/types'


function App() {
  const [Data , setData] = useState<DataApiResponse >({task:[]});  //ApiProps
  const [isLoading, setLoading] = useState(false);
  // const [error, setError] = useState(null);
 
  useEffect(()=>{
    setLoading(true)
    fetch(`https://jsonplaceholder.typicode.com/posts?_limit=8`)
     .then((response) => response.json())      
     .then((Data)=>{
      setData({ task: Data });
      console.log(Data)
    // setLoading(false)
     })
  },[]);

   if(isLoading) return <p> Loading ...Hello World</p>
   if(!Data.task.length) return <p> No data</p>

   return (
    <div className="contianer">

      <ul>{Data && Data.task?[].map((task:ApiProps)=>( 
        <>
        <li key ={task.id}>{task.id}</li>
        <li>{task.title}</li>
        <li>{task.userId}</li>
        <li>{task.body}</li>
        </>
      )):null }</ul>    
    </div>
    );

}

export default App;

Types.tsx

export default interface ApiProps {
    id: number,
    title: string,
    userId:string,
    body:string
}

export interface DataApiResponse {
    task : ApiProps[]
}

Index.tsx

import React from 'react';
import ReactDOM from 'react-dom/client';
import './index.css';
import App from './App';

const root = ReactDOM.createRoot(
  document.getElementById('root') as HTMLElement
);
root.render(
  <React.StrictMode>
    <App/>
  </React.StrictMode>
);

enter image description here

CodePudding user response:

You are removing task from your state

Fix:

setData({ task: Data })

CodePudding user response:

Please make changes to -app.tsx

<div className="App">
 <h1>
 Data from API Response
  </h1>
  <ul>{ Data && Data?.task?.map((dataInt:ApiProps)=>( 
    <>
     <li key={dataInt.id}>{dataInt.id}</li>
    <li>{dataInt.title}</li>
    </>
  )) }</ul>
</div>

Please check above code and replace with your. If you still facing issue lemme know. I will make more changes in code. Thanks

  • Related