swr, the best solution to the API call of React project

swr, the best solution to the API call of React project

After searching around, I feel that there are many articles on learning swr source code, but it seems that the use is indeed limited, so

At present, I feel that using swr is more comfortable than using Redux saga. Firstly, the amount of code is much smaller, and secondly, the operation of synchronous and asynchronous is more concise and clear. swr also supports various API calls very well. The official documents also include the configuration of Axios and GraphQL. Generally speaking, it should be the library that can best solve API calls in React project among some recently used packages.

swr is the abbreviation of stay while revalidate. Stay means to be placed for a long time. I'm not sure how to translate it. It's probably the feeling that the state is placed unchanged but will be revalidated. This is a node package developed by the nextjs team. Its functions include the synchronization of fetch API usage and control management status.

It is a React Hooks in itself, so it is better to use it with React ecosystem (such as Next series). Other frameworks have not been tried, so there is no nonsense here.

fetch API

Reference codes are as follows:

import React, { useState, useEffect } from "react";
import useSWR from "swr";

const fetcher = (...args) => fetch(...args).then((res) => res.json());

const SWR = () => {
  const [products, setProducts] = useState(null);

  const { data, error } = useSWR(
    "https://dummyjson.com/products?limit=10",
    fetcher
  );

  useEffect(() => {
    if (data) {
      setProducts(data.products);
    }
  }, [data]);

  if (error) {
    return <p>Error</p>;
  }

  if (!products) {
    return <p>loading</p>;
  }

  return (
    <div>
      {products.map((product) => {
        return (
          <div key={product.id}>
            <h1>{product.title}</h1>
            <p>{product.description}</p>
          </div>
        );
      })}
    </div>
  );
};

export default SWR;

The display effect is as follows:

useSWR is a hook encapsulated by swr. Using this hook, you can easily obtain the data and error attributes for operation. If swr can only provide these functions, it is the same to encapsulate a custom hook. Why do you have to use swr?

Serial call

Refer to the following codes:

import React, { useState, useEffect } from "react";
import useSWR from "swr";

const fetcher = (...args) => fetch(...args).then((res) => res.json());

console.time("fetching");

const SWR = () => {
  const { data: products, error } = useSWR(
    "https://dummyjson.com/products?limit=1",
    fetcher
  );

  const { data: productDetail, error: productError } = useSWR(
    () => `https://dummyjson.com/products/${products.products[0].id}`,
    fetcher
  );

  console.log(productDetail);

  if (!productDetail) {
    return <p>Loading</p>;
  }

  console.timeLog("fetching");

  return (
    <div>
      <h1>{productDetail.title}</h1>
      <p>{productDetail.description}</p>
    </div>
  );
};

export default SWR;

The rendering result is as follows:

It takes 8000ms to successfully capture the data, and the data can be successfully rendered. In other words, swr obtains the product from the / products API, and then uses the obtained product id to call the operation of product details. There is no superfluous code. Just calling an anonymous function in useSWR completes such a code that applies a lot of thenable.

Code quantity: 2 lines.

Parallel call

swr supports parallel operation by default. Refer to the following code:

import React, { useState, useEffect } from "react";
import useSWR from "swr";

const fetcher = (...args) => fetch(...args).then((res) => res.json());

console.time("fetching");

const SWR = () => {
  const { data: product1, error: err1 } = useSWR(
    "https://dummyjson.com/products/1",
    fetcher
  );
  const { data: product2, error: err2 } = useSWR(
    "https://dummyjson.com/products/2",
    fetcher
  );
  const { data: product3, error: err3 } = useSWR(
    "https://dummyjson.com/products/3",
    fetcher
  );

  if (!product1 || !product2 || !product3) {
    return <p>Loading</p>;
  }

  console.log(product1);
  console.log(product2);
  console.log(product3);

  console.timeLog("fetching");

  return (
    <div>
      <h1>{product1.title}</h1>
      <p>{product1.description}</p>
    </div>
  );
};

export default SWR;

The acquisition time is as follows:

And the data is directly from https://dummyjson.com/products Instead of the local cache. It can also be seen that these requests are issued at the same time, that is, in parallel.

These functions alone have shown the advantages of swr and other third-party libraries, not to mention that in addition to simple API calls, swr also has the function of state management.

Management status

The following is a screenshot from the official document:

swr also has the mode of state management, that is, in the process of losing focus - > regaining focus, swr will revalidate the state.

In the above case, this means that API will be called again, because, of course, because it is a static API, it will return a middle note of 304 to allow the browser to retrieve data from the cache.

In addition to re updating the status during onFocus (on by default), swr also has two options: updating the status through time interval and updating the status during reconnection (on by default). By reasonably matching appropriate options, we can also more easily realize the function with a large amount of original code.

Other functions

swr can also easily implement pagination, which can re call API and update data after monitoring the change of state.

This function, combined with prefetching, can easily realize the real-time jump function of the page.

In addition to the above-mentioned functions, swr also has descriptions of mutation, suspension and other functions. However, since I haven't played the suspension of React yet, and there is no need to toss the configuration for the time being, I won't repeat it here.

Similarly, swr as next JS is part of the ecosystem, which is also targeted at next JS to support SSR and SSG, which is also a feature to be carefully explored in the next step.

Tags: React Next.js

Posted by sahammondsr on Tue, 19 Apr 2022 12:38:06 +0930