Reputation: 1856
I am trying to display data returned from an API call.. API returns something like:
{"id":,"firm":"","office":"","salesCode":"","account":""}
and I have a class like this:
const DataConstructed = items.map((item) =>
<TableRow>
<TableCell>{items.data.f}</TableCell>
<TableCell>{items.data.o}</TableCell>
<TableCell>{items.data.s}</TableCell>
<TableCell>{items.data.a}</TableCell>
</TableRow>
);
render() {
const { classes } = this.props;
const { error, isLoaded, items } = this.state;
if (error) {
return <div>Error: {error.message}</div>;
} else if (!isLoaded) {
return <div>Loading...</div>;
} else {
const DataConstructed = () => {
var data = [];
for(let i=0; i<items.data.length; i++)
{
data.push(
<TableRow>
<TableCell>{items.data[i].f}</TableCell>
<TableCell>{items.data[i].o}</TableCell>
<TableCell>{items.data[i].s}</TableCell>
<TableCell>{items.data[i].a}</TableCell>
</TableRow>
);
}
return data;
}
return (
<Fragment>
<Paper className={classes.Table}>
<Table>
<TableHead className={classes.TableHeader}>
<TableRow>
<TableCell>F</TableCell>
<TableCell>O</TableCell>
<TableCell>S</TableCell>
<TableCell>A</TableCell>
</TableRow>
</TableHead>
<TableBody>
{this.DataConstructed()}
</TableBody>
</Table>
</Paper>
</Fragment>
);
}
}
I get an error saying "TypeError: this.DataConstructed is not a function", I don't understand what the problem is..?
......
Upvotes: 0
Views: 183
Reputation: 1856
Okay, I fixed it like below. It might not be the best way to address this kind of scenario, but it does the job.
Below code goes under the class but outside of render TabularData(items) { var elements = [];
for(let i=0;i<items.data.length;i++)
{
elements.push(
<TableRow>
<TableCell>{items.data[i].f}</TableCell>
<TableCell>{items.data[i].o}</TableCell>
<TableCell>{items.data[i].s}</TableCell>
<TableCell>{items.data[i].a}</TableCell>
</TableRow>
);
}
return elements;
}
Below code goes inside render
{this.TabularData(items)}
Upvotes: 0
Reputation: 2605
Problem:
<TableBody>
{this.DataConstructed()}
</TableBody>
Fix:
<TableBody>
{DataConstructed(items)}
</TableBody>
Upvotes: 0
Reputation: 3887
You should not define your class functions inside your render method.
In your case its just a regular function defined in your render method. You could still make it work. Just remove 'this' from this.DataConstructed as its not a class function.
<TableBody>
{DataConstructed()}
</TableBody>
Upvotes: 1