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 发布文章使用:只允许注册用户才可以访问!


React Query & SWR的更多相关文章

  1. [GraphQL] Apollo React Query Component

    In this lesson I refactor a React component that utilizes the graphql higher-order component to the ...

  2. 写一个react hook:useLoading

    在写业务的过程中,我们总是会遇到这样的需求,在请求时显示一个 loading,然后请求结束后展示数据.以一个是不是 vip 的场景为例,如果不加入 loading 状态,页面可能在未请求的时候显示非 ...

  3. [GraphQL] Fetch Server Data and Client-side State in One Query using React Apollo + GraphQL

    In this lesson we look at how the Apollo @client directive can be used to fetch client-side state al ...

  4. [React Router v4] Parse Query Parameters

    React Router v4 ignores query parameters entirely. That means that it is up to you to parse them so ...

  5. [React + GraphQL] Use useLazyQuery to manually execute a query with Apollo React Hooks

    When using useQuery from Apollo React Hooks, the request will be sent automatically after the compon ...

  6. [React] Create a Query Parameter Modal Route with React Router

    Routes are some times better served as a modal. If you have a modal (like a login modal) that needs ...

  7. webpack+react+redux+es6开发模式

    一.预备知识 node, npm, react, redux, es6, webpack 二.学习资源 ECMAScript 6入门 React和Redux的连接react-redux Redux 入 ...

  8. 构建通用的 React 和 Node 应用

    这是一篇非常优秀的 React 教程,这篇文章对 React 组件.React Router 以及 Node 做了很好的梳理.我是 9 月份读的该文章,当时跟着教程做了一遍,收获很大.但是由于时间原因 ...

  9. react+redux教程(六)redux服务端渲染流程

    今天,我们要讲解的是react+redux服务端渲染.个人认为,react击败angular的真正“杀手锏”就是服务端渲染.我们为什么要实现服务端渲染,主要是为了SEO. 例子 例子仍然是官方的计数器 ...

随机推荐

  1. jmeter报Address already in use: connect

    jmeter报Address already in use: connect   用windows进行jmeter压测出现java.net.BindException: Address already ...

  2. 宝塔Linux命令

    安装宝塔 Centos安装脚本 5.7:yum install -y wget && wget -O install.sh http://download.bt.cn/install/ ...

  3. The Go Blog Getting to Go: The Journey of Go's Garbage Collector

    Getting to Go: The Journey of Go's Garbage Collector https://blog.golang.org/ismmkeynote

  4. dotnet .NET

    小结: 1.一个.NET应用是一个使用.NET Framework类库来编写,并运行于公共语言运行时Common Language Runtime之上的应用程序.       Microsoft .N ...

  5. super 多重继承 super() function with multilevel inheritance

    Python | super() function with multilevel inheritance - GeeksforGeeks https://www.geeksforgeeks.org/ ...

  6. Spring Boot整合Spring Data JPA

    1.JPA 2.Spring Data JPA 3.导入依赖 4.连接数据库 5.实体类 6.Repository 7.测试 1.JPA JPA是Java Persistence API的简称,中文名 ...

  7. linux基础进阶命令详解(输出重定向(2>&1,1>&2,&>file)、输入重定向、管道符、通配符、三种引号、软连接、硬链接、根“/”、绝对路径vs相对路径)

    本章命令(共9个): 1 2 3 4 5 6 7 8 9 输出重定向 输入重定向 管道符 通配符 三种引号 软连接 硬链接 根"/" 绝对路径vs相对路径 1.输出重定向 作用:一 ...

  8. Cisco的互联网络操作系统IOS和安全设备管理器SDM__管理Cisco互联网络

    1.如果不能远程登录到一台设备上,可能是由于远程设备上没有设置口令.也可能是由于访问控制列表过滤了远程登录会话. show users:检查都有哪些设备连接到了此路由器. clear line #:清 ...

  9. 2021 年写 JavaScript 代码的 17 个优化技巧

    我们经常会写一些 JavaScript 代码,但是如何写出干净又易维护的代码呢?本文将讲解 17 个 JavaScript 代码的技术帮助你提高编程水平,此外,本文可以帮助您为 2021 年的 Jav ...

  10. ElasticSearch 安装与运行

    公号:码农充电站pro 主页:https://codeshellme.github.io 本节来介绍 ES 的安装. 1,下载 ES ES 是基于 Java 语言开发的,因此,要安装 ES,首先需要有 ...