Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
183 views
in Technique[技术] by (71.8m points)

react hooks - Unable to render data in Reactjs

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

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

1 Reply

0 votes
by (71.8m points)

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

{data && renderTableData(data)}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...