GithubHelp home page GithubHelp logo

next-fetch's Introduction

Next Fetch

Think in React, instead about routing: Next Fetch is an intuitive way to dynamically fetch data from API endpoints in Next.js, using your favorite libraries.

๐Ÿ’ƒ Import your API endpoints instead of making a stringified dance

๐Ÿ”’ Infer the types end-to-end for your data based on its implementation

โš› Think in React, instead of routing: you only export a React hook!

๐Ÿ•ต Embrace best-practices: input validation, error handling, etc.

๐ŸŒ Use Request and Response classes as building blocks, no matter what runtime you're running on (Node.js or Edge)

๐Ÿ“ Use <Form /> component for making progressive enhanced experiences

๐Ÿคฏ Supports SWR and React Query out of the box!

What does that mean?

Next Fetch is using compile-time transformations to allow you to import your API endpoints instead of referencing them as plain strings, while keeping the type definitions co-located with the implementation.

Next.js + Next Fetch Plain Next.js
API implementation
// pages/api/message.swr.tsx
import { query } from "@next-fetch/swr";
import z from "zod";

export const useMessage = query(
  // use zod for input validation
  z.object({
    name: z.string(),
  }),
  async function ({ name }) {
    // this.request is a `Request` instance
    return { hello: `world, ${name}` };
  }
);
// pages/api/message.tsx
import type { NextApiRequest, NextApiResponse } from "next";

export default (req: NextApiRequest, res: NextApiResponse) => {
  // ad-hoc input validation
  const name = Array.isArray(req.query.name)
    ? req.query.name[0]
    : req.query.name;
  if (!name) {
    return res.status(400).json({ error: "No name provided" });
  }

  // explicit type defniitions required
  return res.status(200).json({ hello: `world, ${name}` });
};
API consumption
import { useMessage } from "./api/message";

export default function MyPage() {
  const { data, error } = useMessage({
    // will autocomplete and
    // type-check the input arguments
    name: "John Doe",
  });

  // autocompletes and type-checks!
  const hello = data?.hello;

  return <div>{/* ... */}</div>;
}
// pages/index.tsx
import useSWR from "swr";

const fetcher = (url: string) => {
  const response = await fetch(url);

  // handle input validation or runtime errors
  if (!response.ok) {
    const text = await response.text().catch(() => null);
    throw new Error(`response is not okay${text ? `: ${text}` : ""}`);
  }

  return await response.json();
};

export default function MyPage() {
  const { data, error } = useSWR("/api/message?name=John%20Doe", fetcher);
  /** `data` is `any`, so we need to explicitly type-cast here */
  return <div>{/* ... */}</div>;
}

next-fetch's People

Contributors

zbndm avatar

Watchers

 avatar

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.