Reputation: 5
index.js
export default class App extends React.Component {
state = {
data: [],
filteredData: [],
columns: [],
searchInput: ""
};
componentDidMount() {
this.getData();
this.getColumns();
}
render() {
const getColumns = () => {
let columns = [
{
Header: "First Name",
accessor: "firstName",
sortable: false,
show: true,
displayValue: " First Name"
},
{
Header: "Status",
accessor: "status",
sortable: false,
show: true,
displayValue: "Status "
},
{
Header: "Visits",
accessor: "visits",
sortable: false,
show: true,
displayValue: " Visits "
}
];
this.setState({ columns });
};
const getData = () => {
let data = [
{ firstName: "test1", status: "hi1", visits: 155 },
{ firstName: "test2", status: "hi2", visits: 155 },
];
this.setState({ data, filteredData: data });
};
const handleSetData = (data) => {
console.log(data);
this.setState({ filteredData: data });
};
let { filteredData, columns } = this.state;
return (
<div>
<test
data={this.state.data}
handleSetData={this.handleSetData}
/>
<ReactTable
data={filteredData}
columns={columns}
defaultPageSize={10}
className="-striped -highlight"
/>
</div>
);
}
}
error code
TypeError
this.getData is not a function
App.componentDidMount
/src/index.js:17:11
14 | };
15 |
16 | componentDidMount() {
> 17 | this.getData();
| ^
18 | this.getColumns();
19 | }
20 |
I am currently practicing because I want to implement the search function. I want it to work without changing the current code location. I will post more code if needed. How to enable getData and get columns from componentDidMount? Let me know if you know the answer! thank you for the reply.
Upvotes: 0
Views: 4234
Reputation: 5054
You can't setState
inside render. You need to write function outside render
that's why its giving error. As it can't find out the functions. You need to do like this:
export default class App extends React.Component {
state = {
data: [],
filteredData: [],
columns: [],
searchInput: ""
};
componentDidMount() {
this.getData();
this.getColumns();
}
getColumns = () => {
let columns = [
{
Header: "First Name",
accessor: "firstName",
sortable: false,
show: true,
displayValue: " First Name"
},
{
Header: "Status",
accessor: "status",
sortable: false,
show: true,
displayValue: "Status "
},
{
Header: "Visits",
accessor: "visits",
sortable: false,
show: true,
displayValue: " Visits "
}
];
this.setState({ columns });
};
getData = () => {
let data = [
{ firstName: "test1", status: "hi1", visits: 155 },
{ firstName: "test2", status: "hi2", visits: 155 },
];
this.setState({ data, filteredData: data });
};
handleSetData = (data) => {
console.log(data);
this.setState({ filteredData: data });
};
render() {
let { filteredData, columns } = this.state;
return (
<div>
<test
data={this.state.data}
handleSetData={this.handleSetData}
/>
<ReactTable
data={filteredData}
columns={columns}
defaultPageSize={10}
className="-striped -highlight"
/>
</div>
);
}
}
Upvotes: 1