5.10 Next.js Building a Car Trader App #5- Pagination with filters for the list of cars

Hoàn thiện chức năng phân trang :)

C:\Users\Administrator\Desktop\pro\pages\api\cars.ts

import { NextApiRequest, NextApiResponse } from 'next';
import  getPaginatedCars  from '../database/getPaginatedCars';
export default async function cars(
  req: NextApiRequest,
  res: NextApiResponse
) {
  const cars = await getPaginatedCars(req.query);
  res.json(cars);
}

C:\Users\Administrator\Desktop\pro\pages\cars.tsx

import { Grid, Card, CardHeader, Avatar, IconButton, CardMedia, Typography, makeStyles } from '@material-ui/core';
import MoreVertIcon from '@material-ui/icons/MoreVert';
import CardContent from '@material-ui/core/CardContent';
import deepEqual from 'fast-deep-equal';
import { GetServerSideProps } from 'next';
import { useRouter } from 'next/router';
import { stringify } from 'querystring';
import { useState } from 'react';
import useSWR from 'swr';
import Search from '.';
import { CarModel } from './api/Car';
import  CarCard  from '../components/CarCard';
import Link from 'next/link';
import { getMakes, Make } from './database/getMakes';
import { getModels, Model } from './database/getModels';
import  getPaginatedCars  from './database/getPaginatedCars';
import  getAsString  from '../getAsString';
import CarPagination  from '../components/CarPagination';
export interface CarsListProps {
  makes: Make[];
  models: Model[];
  cars: CarModel[];
  totalPages: number;
}
const useStyles = makeStyles((theme) => ({
  media: {
    height: 0,
    paddingTop: '56.25%', // 16:9
  },
  expand: {
    transform: 'rotate(0deg)',
    marginLeft: 'auto',
    transition: theme.transitions.create('transform', {
      duration: theme.transitions.duration.shortest,
    }),
  },
  expandOpen: {
    transform: 'rotate(180deg)',
  },
  avatar: {
    backgroundColor: 'red',
  },
  achorTag: {
      textDecoration: 'none'
  }
}));
export default function CarsList({makes, models, cars, totalPages }:CarsListProps) {
  const classes = useStyles();
  const { query } = useRouter();
  const [serverQuery] = useState(query);
  const { data } = useSWR('/api/cars?' + stringify(query), {
    dedupingInterval: 15000,
    initialData: deepEqual(query, serverQuery) ? { cars, totalPages } : undefined
  });
  return (
    <Grid container spacing={3}>
      <Grid item xs={12} sm={5} md={3} lg={2}>
        <Search makes={makes} models={models} />
      </Grid>
      <Grid container item xs={12} sm={7} md={9} lg={10} spacing={3}>
        <Grid item xs={12}>
          <CarPagination totalPages={data?.totalPages} />
        </Grid>
        {(data?.cars || []).map((car) => (
          <Grid key={car.id} item xs={12} sm={6}>
            <CarCard car={car} />
          </Grid>
        ))}
        <Grid item xs={12}>
          <CarPagination totalPages={data?.totalPages} />
        </Grid>
      </Grid>
    </Grid>
  );
}
export const getServerSideProps: GetServerSideProps<CarsListProps> = async (ctx) => {
  const make = getAsString(ctx.query.make);
  const [makes, models, pagination] = await Promise.all([getMakes(),getModels(make),getPaginatedCars(ctx.query)]);
  return {
    props: {makes, models,cars: pagination.cars, totalPages: pagination.totalPages}
  }
}

Last updated

Was this helpful?