I am following some tutorials on youtube, he is showing data succesfully but it is hard coded data, and I want to take data from backend. Data is coming successfully(I see it on console with console.log) but I could not show in table.
Here is my code:
import React, { useEffect, useState } from 'react';
import * as ReactBootStrap from 'react-bootstrap';
import * as service from '../service/FetchCustomerService';
function MainPanel() {
const [customers, setCustomers] = useState([]);
useEffect(() => {
const fetchPostList = async () => {
const response = await service.getCustomerList();
setCustomers({ response });
console.log(response.data)
};
fetchPostList()
}, [setCustomers]);
return (
<ReactBootStrap.Table striped bordered hover>
<thead>
<tr>
<th>ID</th>
<th>FirstName</th>
<th>LastName</th>
</tr>
</thead>
<tbody>
{customers &&
customers.map((item) => (
<tr key={item.id}>
<td>{item.id}</td>
<td>{item.firstName}</td>
<td>{item.lastName}</td>
</tr>
))}
</body>
</ReactBootStrap.Table>
);
}
export default MainPanel;
Here is async service method to get data:
export async function getCustomerList() {
return axios.get("http://localhost:8080/customer/list");
}
Backend is returning 5 data in a list successfully but I could not show it on table. In example console output is that first printing the list successfully and then
Uncaught TypeError: customers.map is not a function
at MainPanel (MainPanel.js:29:1)
at renderWithHooks (react-dom.development.js:16141:1)
at updateFunctionComponent (react-dom.development.js:20313:1)
at beginWork (react-dom.development.js:22356:1)
at HTMLUnknownElement.callCallback (react-dom.development.js:4157:1)
at Object.invokeGuardedCallbackDev (react-dom.development.js:4206:1)
at invokeGuardedCallback (react-dom.development.js:4270:1)
at beginWork$1 (react-dom.development.js:27243:1)
at performUnitOfWork (react-dom.development.js:26392:1)
at workLoopSync (react-dom.development.js:26303:1)
How can I show the data ?
CodePudding user response:
You can get result from API by response.data
when using axios
.
You don't need to add setCustomers
(React setState
function) because it is created by useState
.
According to React documentation,
React guarantees that setState function identity is stable and won’t change on re-renders. This is why it’s safe to omit from the useEffect or useCallback dependency list.
useEffect(() => {
const fetchPostList = async () => {
const response = await service.getCustomerList();
setCustomers(response.data);
console.log(response.data)
};
fetchPostList()
}, []);