zoukankan      html  css  js  c++  java
  • xgqfrms™, xgqfrms® : xgqfrms's offical website of GitHub!

    React Query & SWR

    HTTP request all in one solution

    React Query

    Hooks for fetching, caching and updating asynchronous data in React

    https://react-query.tanstack.com/

    https://github.com/tannerlinsley/react-query

    /* eslint-disable jsx-a11y/anchor-is-valid */
    import React from "react";
    import ReactDOM from "react-dom";
    import axios from "axios";
    import {
      useQuery,
      useQueryCache,
      QueryCache,
      ReactQueryCacheProvider,
    } from "react-query";
    import { ReactQueryDevtools } from "react-query-devtools";
    
    const queryCache = new QueryCache();
    
    function App() {
      const [postId, setPostId] = React.useState(-1);
    
      return (
        <ReactQueryCacheProvider queryCache={queryCache}>
          <p>
            As you visit the posts below, you will notice them in a loading state
            the first time you load them. However, after you return to this list and
            click on any posts you have already visited again, you will see them
            load instantly and background refresh right before your eyes!{" "}
            <strong>
              (You may need to throttle your network speed to simulate longer
              loading sequences)
            </strong>
          </p>
          {postId > -1 ? (
            <Post postId={postId} setPostId={setPostId} />
          ) : (
            <Posts setPostId={setPostId} />
          )}
          <ReactQueryDevtools initialIsOpen />
        </ReactQueryCacheProvider>
      );
    }
    
    function usePosts() {
      return useQuery("posts", async () => {
        const { data } = await axios.get(
          "https://jsonplaceholder.typicode.com/posts"
        );
        return data;
      });
    }
    
    function Posts({ setPostId }) {
      const cache = useQueryCache();
      const { status, data, error, isFetching } = usePosts();
    
      return (
        <div>
          <h1>Posts</h1>
          <div>
            {status === "loading" ? (
              "Loading..."
            ) : status === "error" ? (
              <span>Error: {error.message}</span>
            ) : (
              <>
                <div>
                  {data.map((post) => (
                    <p key={post.id}>
                      <a
                        onClick={() => setPostId(post.id)}
                        href="#"
                        style={
                          // We can use the queryCache here to show bold links for
                          // ones that are cached
                          cache.getQueryData(["post", post.id])
                            ? {
                                fontWeight: "bold",
                                color: "green",
                              }
                            : {}
                        }
                      >
                        {post.title}
                      </a>
                    </p>
                  ))}
                </div>
                <div>{isFetching ? "Background Updating..." : " "}</div>
              </>
            )}
          </div>
        </div>
      );
    }
    
    const getPostById = async (key, id) => {
      const { data } = await axios.get(
        `https://jsonplaceholder.typicode.com/posts/${id}`
      );
      return data;
    };
    
    function usePost(postId) {
      return useQuery(["post", postId], getPostById, {
        enabled: postId,
      });
    }
    
    function Post({ postId, setPostId }) {
      const { status, data, error, isFetching } = usePost(postId);
    
      return (
        <div>
          <div>
            <a onClick={() => setPostId(-1)} href="#">
              Back
            </a>
          </div>
          {!postId || status === "loading" ? (
            "Loading..."
          ) : status === "error" ? (
            <span>Error: {error.message}</span>
          ) : (
            <>
              <h1>{data.title}</h1>
              <div>
                <p>{data.body}</p>
              </div>
              <div>{isFetching ? "Background Updating..." : " "}</div>
            </>
          )}
        </div>
      );
    }
    
    const rootElement = document.getElementById("root");
    ReactDOM.render(<App />, rootElement);
    
    
    

    SWR

    React Hooks library for data fetching

    https://swr.vercel.app/

    // fetcher
    
    export function fetcher() {
      return fetch(`${process.env.REACT_APP_API_BASE_URL}users`).then(response =>
        response.json()
      );
    }
    
    
    
    
    import useSWR from 'swr';
    
    function Profile() {
      const { data, error } = useSWR('/api/user', fetcher)
      if (error) return <div>failed to load</div>
      if (!data) return <div>loading...</div>
      return <div>hello {data.name}!</div>
    }
    
    

    demo

    https://codesandbox.io/s/4-ways-to-handle-restful-http-in-react-41j83

    https://codesandbox.io/s/react-query-hooks-ss7o0

    https://www.dataformsjs.com/examples/countries-no-spa-react.htm

    refs

    https://codesandbox.io/s/4-ways-to-handle-restful-http-in-react-k3xug

    https://codesandbox.io/s/github/tannerlinsley/react-query/tree/master/examples/basic?from-embed



    ©xgqfrms 2012-2020

    www.cnblogs.com 发布文章使用:只允许注册用户才可以访问!


  • 相关阅读:
    2016-06-06:X264码率控制
    2016-04-12:图像差异查找算法
    2016-03-24:Windows内存泄露分析工具
    2016-03-15:关于VS中模块定义文件
    2016-03-10:libx265源码解析
    MSSQL字符串取相应的第几个数组值
    MSSQL字符串分割
    list 属性字段直接转成字符串数组
    WebApiTestClient
    获取文件路径
  • 原文地址:https://www.cnblogs.com/xgqfrms/p/13938962.html
Copyright © 2011-2022 走看看