1

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.

4
  • Maybe fetch(..).then(response => response.json()).then(json => {...}) Commented Dec 20, 2020 at 17:54
  • Also try to initialise your default data as empty array like const [data, setData] = useState({data:[]}); this way you can return ( {data.lenght > 0 && .... Commented Dec 20, 2020 at 17:57
  • Pass data to your renderTableData() function. Commented Dec 20, 2020 at 18:11
  • @ToddSkelton I tried that as well {renderTableData({data})} but it's not working throwing error data.map is not a function Commented Dec 20, 2020 at 18:13

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

11 Comments

@Mahesh Please console.log data first to see what you are passing
@Mahesh this is before you set it to something. Use initial value of [] instead of '' in useState.
just replaced [] in place of '' and the data got rendered perfectly. Thank you so much @giorgim
@Mahesh map is a function which should be called on array, not string
@Mahesh It is better to not ignore it, here is some reading about it: reactjs.org/docs/lists-and-keys.html
|
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.