Home > Software engineering >  There is a problem with fetching and parsing data with React and Javascript
There is a problem with fetching and parsing data with React and Javascript

Time:06-30

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
 };

CodePudding user response:

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([]);
  • Related