Mahesh
Mahesh

Reputation: 1333

Unable to render Table in Reactjs

I am trying to hit an api(sample response) which gives list of objects and render it in a table in react. Following is my code. I am getting error as data is not defined

Here is the code when I hardcoded data, the table got rendered perfectly

import React, { useEffect, useState } from "react";

function renderTableData() {
    return data.map((student, index) => {
        const { config, text, source_link, tab_type } = student //destructuring
        return (
            <tr key={config}>
                <td>{config}</td>
                <td>{text}</td>
                <td>{source_link}</td>
                <td>{tab_type}</td>
            </tr>
        )
    })
}

const useFetch = (url) => {
    const [data, setData] = useState('');
    const [loading, setLoading] = useState(true);
    useEffect(async () => {
        const response = await fetch(url, {
            method: 'GET',
        })
        const data = await response.json()
        console.log(data)
        setData(data)
        setLoading(false)
    }, []);
    return { data, loading };
}

export default function CreateTestcaseStep2() {
    const { data, loading } = useFetch(ENPOINT_URL_GOES_HERE)

    return (
        <div>
            <h1 id='title'>React Dynamic Table</h1>
            <table id='students'>
                <tbody>
                    {renderTableData()}
                </tbody>
            </table>
        </div>
    );
}

Please suggest where I am doing wrong as renderTableData function is not able get the data object.

Upvotes: 1

Views: 569

Answers (2)

Giorgi Moniava
Giorgi Moniava

Reputation: 28654

renderTableData is defined outside your functional component and you refer to data variable within it, I suppose it doesn't know which data variable to refer to? I am surprised you didn't get an error about this.

Try passing the data variable as parameter to the function.

Upvotes: 1

Fiodorov Andrei
Fiodorov Andrei

Reputation: 2018

I'm refactor you example.

Do not use useEffect asyc.

useEffect(() => {
    axios.get(url).then((response) => {
      setData(response);
      setLoading(false);
    });
}, [url]);

If you want to make table body with a function, need to pass data using parameters.

const renderTableData = (data) => {
                      // ^^^^  Pass data using function parameters, 
                      // this function it's possible to use in another table with the same data
  return data?.map((student) => {
    const { id, name, username, email } = student;
    return (
      <tr key={id}>
        <td>{name}</td>
        <td>{username}</td>
        <td>{email}</td>
      </tr>
    );
  });
};

To render table body with function pass state

<tbody>{renderTableData(data)}</tbody>
                     // ^^^^ Passing state to render table body

See live demo, pass data into function using params:

Edit elated-hill-symxk

Upvotes: 0

Related Questions