Home > Software design >  Cannot read properties of undefined array
Cannot read properties of undefined array

Time:10-16

I'm quite new to React and typescript, trying to build simple application which extracts data from API and displays it on web page. I tried couple of things after reading some articles online but unfortunately I keep getting below error. can you please advise on what could be the issue.

Error:

Uncaught TypeError: Cannot read properties of undefined (reading 'map')

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:[]});  
 
  useEffect(()=>{

    fetch(`https://jsonplaceholder.typicode.com/posts?_limit=8`)
     .then((response) => {
            return response.json()
     })      
     .then((Data)=>{
      setData({task:Data});
      //setError(null);
      console.log(Data)
      
     })
  },[])

  return (

    <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>
   
  );
}

export default App;

Types.tsx

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

export interface DataApiResponse {
    task : ApiProps[]
}

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