I am trying to convert the following snippet of code to use functional based components.
class IssueTable extends React.Component {
constructor() {
super();
this.state = { issues: [] };
setTimeout(() => {
this.createIssue(sampleIssue);
}, 2000);
}
componentDidMount() {
this.loadData();
}
loadData() {
setTimeout(() => {
this.setState({ issues: initialIssues });
}, 500);
}
createIssue(issue) {
issue.id = this.state.issues.length + 1;
issue.created = new Date();
const newIssueList = this.state.issues.slice();
newIssueList.push(issue);
this.setState({ issues: newIssueList });
}
render() {
const issueRows = this.state.issues.map(issue =>
<IssueRow key={issue.id} issue={issue} />
);
return (
<table className="bordered-table">
<thead>
<tr>
<th>ID</th>
<th>Status</th>
<th>Owner</th>
<th>Created</th>
<th>Effort</th>
<th>Due Date</th>
<th>Title</th>
</tr>
</thead>
<tbody>
{issueRows}
</tbody>
</table>
);
}
}
While trying to convert it the table somehow keeps rerendering and I get the key not unique error. I used useEffect but I dont know how to use constructor like functionality. How to use functions to achieve it. (issueRows is a component which takes care of the row data in the table). The functional version is shown below:
function IssueTable(){
const [issue1, setIssues] = React.useState([]);
React.useEffect(()=>{loadData()},[]);
setTimeout(() => {
createIssue(sampleIssue);
}, 2000);
function loadData() {
setTimeout(() => {
setIssues(issues);
}, 500);
}
function createIssue(issue) {
issue.id = issue1.length+1;
issue.created = new Date();
const newIssueList = issue1.slice();
newIssueList.push(issue);
setIssues(newIssueList);
}
const issueRows = issue1.map(issue =>
<IssueRow key={issue.id} issue={issue} />
)
return <table className="bordered-table">
<thead>
<tr>
<th>ID</th>
<th>Status</th>
<th>Owner</th>
<th>Created</th>
<th>Effort</th>
<th>Due Date</th>
<th>Title</th>
</tr>
</thead>
<tbody>
{issueRows}
</tbody>
</table>
}
function IssueRow(props){
return(
<tr>
<td>{props.issue.id}</td>
<td>{props.issue.status}</td>
<td>{props.issue.owner}</td>
<td>{props.issue.created.toDateString()}</td>
<td>{props.issue.effort}</td>
<td>{props.issue.due?props.issue.due.toDateString():""}</td>
<td>{props.issue.title}</td>
</tr>
);
}
sampleIssueandissues? They are never defined in your functional component.