React Query & SWR
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
// 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的更多相关文章
- [GraphQL] Apollo React Query Component
In this lesson I refactor a React component that utilizes the graphql higher-order component to the ...
- 写一个react hook:useLoading
在写业务的过程中,我们总是会遇到这样的需求,在请求时显示一个 loading,然后请求结束后展示数据.以一个是不是 vip 的场景为例,如果不加入 loading 状态,页面可能在未请求的时候显示非 ...
- [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 ...
- [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 ...
- [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 ...
- [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 ...
- webpack+react+redux+es6开发模式
一.预备知识 node, npm, react, redux, es6, webpack 二.学习资源 ECMAScript 6入门 React和Redux的连接react-redux Redux 入 ...
- 构建通用的 React 和 Node 应用
这是一篇非常优秀的 React 教程,这篇文章对 React 组件.React Router 以及 Node 做了很好的梳理.我是 9 月份读的该文章,当时跟着教程做了一遍,收获很大.但是由于时间原因 ...
- react+redux教程(六)redux服务端渲染流程
今天,我们要讲解的是react+redux服务端渲染.个人认为,react击败angular的真正“杀手锏”就是服务端渲染.我们为什么要实现服务端渲染,主要是为了SEO. 例子 例子仍然是官方的计数器 ...
随机推荐
- 转 Fiddler5 发送HTTP请求
Fiddler5 发送HTTP请求 文章转自:https://www.cnblogs.com/zhengna/p/10879573.html 1.Fiddler Composer发送HTTP请求 C ...
- Bitter.Core系列九:Bitter ORM NETCORE ORM 全网最粗暴简单易用高性能的 NETCore 之 WITH 子句支持
有时我们在聚合查询中,经常会有复杂的聚联查询.有时表的聚联查询SQL 子句比较复杂,DBA 会经常告诉们,能否通过WITH 子句优化.WITH 子句,是对SQL 聚联查询的优化.Bitter.Core ...
- IDEA SSM+MAVEN+JWT 图书管理系统
压缩包内含有MAVEN,TOMCAT,需要手动对IDEA进行配置.同时也包含数据库文件. 项目搭载了swagger,可以方便地对接口进行测试 在开发的过程中我也进行了一些记录,可以参考https:// ...
- IDEA安装问题解决
一,安装正确的jdk和idea版本 首先在控制面查看电脑位数,电脑是64位的,安装64位的jdk和idea 二.打开正常的快捷键 有两个启动项,打开对应位数的 三,权限问题 如果弹出不能加载jvm的提 ...
- Compose 定位是 「定义和运行多个 Docker 容器的应用(Defining and running multi-container Docker applications)」
Compose 简介 | Docker 从入门到实践 https://vuepress.mirror.docker-practice.com/compose/introduction.html Com ...
- 思考gRPC :为什么是HTTP/2
Introducing gRPC Support with NGINX 1.13.10 - NGINX https://www.nginx.com/blog/nginx-1-13-10-grpc/ 思 ...
- 一文带你看遍 JDK9~14 的重要新特性!
Java9 发布于 2017 年 9 月 21 日 .作为 Java8 之后 3 年半才发布的新版本,Java 9 带 来了很多重大的变化其中最重要的改动是 Java 平台模块系统的引入,其他还有诸如 ...
- 令牌桶、漏斗、冷启动限流在sentinel的应用
分布式系统为了保证系统稳定性,在服务治理的限流中会根据不同场景进行限流操作,常见的限流算法有: 令牌桶:可容忍一定突发流量的速率的限流,令牌桶算法的原理是系统以恒定的速率产生令牌,然后把令牌放到令牌桶 ...
- php中两个函数可能导致的sql注入
sprintf https://www.php.net/manual/zh/function.sprintf.php 漏洞demo: <?php $name = addslashes($_GET ...
- tp6.0配置站点后无法访问
1.安装composer中国镜像composer config -g repo.packagist composer https://packagist.phpcomposer.com2.执行comp ...