Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I am new to react and have been debugging this from yesterday and I finally decide to post as I am clueless of what is happening.

The following react code fetches data from the api and then renders it on the UI. But, there are few strange things happening here.

I get error saying as TypeError: Cannot read property 'map' of undefined initially but when I comment out {renderTableData(data)}& save and then again uncomment & save, the data is rendering perfectly on the UI

enter image description here

I am thinking that before even the data gets fetched from API, it is getting passed to the function renderTableData which is why in the console undefined is printed.

Here is the code

export default function TenantList(){
  const [data, setData] = useState([]);
    useEffect(() => {
      fetch('https://jsonplaceholder.typicode.com/users').then((response)=>{
        return response.json();
      }).then((data)=>{
        setData(data)
      })
    },[]);
 
function renderTableData(data) {
  console.log("hello ", data)
  return data.map((student, index) => {
      const { name, email } = student //destructuring
      return (
          <tr key={name}>
              <td>{name}</td>
              <td>{email}</td>
          </tr>
      )
  })
}
  return (
    <>
      <div>
        {renderTableData(data)}
      </div>
    </>
  )
}

Please suggest a workaround

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
181 views
Welcome To Ask or Share your Answers For Others

1 Answer

You only want to run this function if you have the data, so check for it:

{data && renderTableData(data)}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...