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. logging philosophy 日志哲学

    Go kit - Frequently asked questions https://gokit.io/faq/ Logging - Why is package log so different? ...

  2. 6到8个月如何达到三年加得前端经验,对标P7,“慕课网 Java工程师2020”

    百度网盘链接:https://pan.baidu.com/s/1xshLRO3ru0LAsQQ0pE67Qg 提取码:bh9f   阶段一:课程设计及前端创建脚手架开发 第1周   需求分析和架构设计 ...

  3. loj10003加工生产调度

    题目描述 某工厂收到了 n个产品的订单,这  个产品分别在 A.B 两个车间加工,并且必须先在 A 车间加工后才可以到 B 车间加工. 某个产品 i 在 A,B 两车间加工的时间分别为 A_i,B_i ...

  4. C#编写一个在asp.net core 3.1下的简单的corn模式的计划任务和一个更简单的定时器类

    asp.net core 下,新增了一个BackgroundService用来实现能在后台跑一个长久运行的任务,因此,也可以用来替换掉原来使用的static的Timer组件, Timer组件主要有以下 ...

  5. 详述C++casting操作

    Casting----类型转换,也就是将数据从一种类型转换到另一种类型的操作.本文首先给出两种类型转换的方式:隐式转换和显式转换,然后简单介绍一下C语言常用的类型转换方式,最后详细叙述C++中常用的三 ...

  6. 使用Docker部署监控系统,Prometheus,Grafana,监控服务器信息及Mysql

    使用Docker部署监控系统,Prometheus,Grafana,监控服务器信息及Mysql 一.docker部署prometheus监控系统 1.1 配置安装环境 1.1.1 安装promethe ...

  7. python——模块、标准库、第三方模块安装

    模块(module)简介 模块化--指将一个完整的程序分解为一个一个小的模块,通过将模块组合,来搭建出一个完整的程序. 模块化的特点: ① 方便开发 ② 方便维护 ③ 模块可以复用! 在Python中 ...

  8. 27.SELinux 安全子系统

    1.SELinux(Security-Enhanced Linux)是美国国家安全局在Linux 开源社区的帮助下开发的一个强制访问控制(MAC,Mandatory Access Control)的安 ...

  9. centos 7 部署nginx及libfastcommon

    1.编译环境 (centos)yum install git gcc gcc-c++ make automake autoconf libtool pcre pcre-devel zlib zlib- ...

  10. c++bind函数使用

    总述     最近写代码的时候看到代码使用了bind,一个参数绑定的标准库函数.程序是这么写的, speaker_play_routine_ = new boost::thread (boost::b ...