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. Linux日志文件(常见)及其功能

    日志文件是重要的系统信息文件,其中记录了许多重要的系统事件,包括用户的登录信息.系统的启动信息.系统的安全信息.邮件相关信息.各种服务相关信息等.这些信息有些非常敏感,所以在 Linux 中这些日志文 ...

  2. Connections could not be acquired from the underlying database!

    Connections could not be acquired from the underlying database! 报错截图: 报错内容: Exception in thread &quo ...

  3. 记一次压测问题定位:connection reset by peer,TCP三次握手后服务端发送RST_网络_c359719435的专栏-CSDN博客 https://blog.csdn.net/c359719435/article/details/80300433

    记一次压测问题定位:connection reset by peer,TCP三次握手后服务端发送RST_网络_c359719435的专栏-CSDN博客 https://blog.csdn.net/c3 ...

  4. (001)每日SQL学习:关于UNION的使用

    union内部必须有相同的列或者相同的数据类型,同时,每条 SELECT 语句中的列的顺序必须相同.union合并了select的结果集. union 与union all的不同: union合并了重 ...

  5. CPU处理器架构和工作原理浅析

    CPU处理器架构和工作原理浅析 http://c.biancheng.net/view/3456.html 汇编语言是学习计算机如何工作的很好的工具,它需要我们具备计算机硬件的工作知识. 基本微机设计 ...

  6. Docker综述

    Docker综述 1.Docker是干什么的? 2.Docker的核心:镜像.容器.仓库 2.1 容器与虚拟机的区别 2.2 仓库 Docker作用 3.Docker的使用 1.Docker是干什么的 ...

  7. vb.net和C#两兄弟谁的封装性更好?

    引言: 虽然没怎样接触过vb.net,但是大概对于vb6还是比较了解的.前者是从后者基础上发展而来的.后来接触了C#编程语言,起初没有太关心她和vb.net有啥不同的地方,话说都是面向对象的,而且都是 ...

  8. 给jekyll博客添加搜索功能

    使用SWIFTYPE为jekyll博客添加搜索引擎 步骤 1.首先去swiftype注册一个账号 2.接着添加自己想要配置的网站地址并为新设定的引擎添加一个名字(非会员只能设置一个引擎). 3.收到验 ...

  9. P2805 [NOI2009]植物大战僵尸 (拓扑排序 + 最小割)

    题意:N*M的矩阵 每个点上都有一颗植物 僵尸只能从每一行的最右边向左进攻 每个植物有攻击范围 可以保护在攻击范围内的植物 同时每一颗植物也保护他左边的植物 摧毁每个植物能获得价值 如果这个植物被保护 ...

  10. fzu2178礼物分配 (状压+二分)

    Problem Description 在双胞胎兄弟Eric与R.W的生日会上,他们共收到了N个礼物,生日过后他们决定分配这N个礼物(numv+numw=N).对于每个礼物他们俩有着各自心中的价值vi ...