0

I'm trying to fetch data from api and show it with React. However I could see that errors and I'm difficult with parsing json response from api. I think that it will be solved if I make response as array. I don't know how to make it.

enter image description here

page.js

  • I try to fetch data from API by Native hook and useEffect
  • I checked API by Postman. So it is working well.
function Customers(props) {
  const [data, setData] = useState({});
  const [error, setError] = useState(null);

  useEffect(() => {
      fetch("http://localhost:8080/contacts")
      .then((response) => {
      if (response.status !== 200) {
          setError("Invalid response: ", response.status);
      } else {
          setError(null);
      }
          return response.json();
      })
      .then((json) => {
        setData(json);
      });
  });

  if (error !== null) {
      return <div>Error: {error.message}</div>
  } else {
      return (
        <DashboardLayout>
        <>
      <Head>
        <title>
          Data
        </title>
      </Head>
      <Box
        component="main"
        sx={{
          flexGrow: 1,
          py: 8
        }}
      >
        <Container maxWidth={false}>
          <Box sx={{ mt: 3 }}>
            <CustomerListResults customers={data} />
          </Box>
        </Container>
      </Box>
    </>
    </DashboardLayout>
        );
  }
}

export default Customers;

list_component.js

  • I made a table. I would like to show API data this table.
  • I try to use slice and map to parsing data. but it is not working.
export const CustomerListResults = ({ customers, ...rest }) => {
  const [limit, setLimit] = useState(25);
  const [page, setPage] = useState(0);

  const handlePageChange = (event, newPage) => {
    setPage(newPage);
  };

  return (
    <Card {...rest}>
      <PerfectScrollbar>
        <Box sx={{ minWidth: 1050 }}>
          <Table size="small">
            <TableHead>
              <TableRow>
                <TableCell>
                  Date
                </TableCell>
                <TableCell>
                  Name
                </TableCell>
              </TableRow>
            </TableHead>
            <TableBody>
            {customers.slice(0,limit).map((customer) => (
                <TableRow
                  hover
                  key={customers.id}
                >
                  <TableCell>
                    <Box
                      sx={{
                        alignItems: 'center',
                        display: 'flex'
                      }}
                    >
                      <Typography
                        color="textPrimary"
                        variant="body2"
                      >
                        {customers.created_date}
                      </Typography>
                    </Box>
                  </TableCell>
                  <TableCell>
                    {customers.user_idx}
                  </TableCell>
                 </TableRow>
              ))}
            </TableBody>
          </Table>
        </Box>
      </PerfectScrollbar>
      <TablePagination
        component="div"
        count={customers.length}
        onPageChange={handlePageChange}
        page={page}
        rowsPerPage={limit}
      />
    </Card>
  );
};

CustomerListResults.propTypes = {
   customers: PropTypes.array.isRequired
 };

1 Answer 1

1

That's because data on initial load is equal to an empty object, and object doesn't have a slice method as it's a method for an array.

One solution is set an inital value for data to an empty array.

const [data, setData] = useState([]);
Sign up to request clarification or add additional context in comments.

15 Comments

Instead use a null value initially and when mapping/slicing, do customers?.slice (notice the optional chaining operator). Also, having the value null/undefined initially will return false in if checks.
Yes, there are multiple ways to solve this issue.
But I prefer the array solution as it doesn't require value checking on the side of HTML.
set initialState as array and when redering the data just puts cutomers && cutomers?.slice it should solve the problem
Good @Mina you are right
|

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.