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. pytest:通过scope控制fixture的作用范围

    一.fixture里面有个参数scope,通过scope可以控制fixture的作用范围,根据作用范围大小划分:session>module>class>function,具体作用范 ...

  2. spring data JPA 使用EntityentiListeners实现数据审计功能设计

    当系统中有审计需求时,特别是需要对某些数据进行动态监控时,我们可以使用EntityentiListeners来实现,当然这是基于使用JPA而不是mybatis的情况下. 当前我们的需求场景: 1.需要 ...

  3. 配置MySQL主从复制报错Last_IO_Error: Fatal error: The slave I/O thread stops because master and slave have equal MySQL server ids; these ids must be different for replication to work

    配置MySQL主从复制报错 ``` Last_IO_Error: Fatal error: The slave I/O thread stops because master and slave ha ...

  4. The Node.js Event Loop, Timers, and process.nextTick()

    The Node.js Event Loop, Timers, and process.nextTick() | Node.js https://nodejs.org/uk/docs/guides/e ...

  5. (Oracle)取当前日期的最近工作日

      描述:现有一需求,日期表中存放了日期和是否节假日(0-工作日,1-节假日),现在需要取日期表中的最近的工作日.如2017/07/23(周日)最近的工作日应该是2017/07/21(周五).     ...

  6. php中两个函数可能导致的sql注入

    sprintf https://www.php.net/manual/zh/function.sprintf.php 漏洞demo: <?php $name = addslashes($_GET ...

  7. Oracle删除表中的重复数据

    Oracle数据库删除表中的重复数据,只保留其中的一条,以两个字段为例,提供两种方法 ①.直接delete重复的数据 delete from table_name t1 where (t1.col1, ...

  8. Language Guide (proto3) | proto3 语言指南(三)默认值

    默认值 解析消息时,如果编码的消息不包含特定的单数元素,则解析对象中的相应字段将设置为该字段的默认值.这些默认值是特定于类型的: string:默认值为空字符串 bytes:默认值为空字节 boole ...

  9. c++复习笔记(3)

    这篇是各种琐碎的东西. 类的函数如果在类内部直接实现,则成为内联函数候选.类外部实现的方法,可以用inline声明,使其称为内联函数候选.但是函数是否可以成为内联函数,需要看编译器的行为.. 构造函数 ...

  10. eclipse下执行maprdeuc程序报错 java.lang.ClassNotFoundException

    最近遇到一个问题,不知怎么突然运行hadoop的map程序报错,困扰了我很久,现在来给大家分享分享.. 错误信息 2017-05-18 21:34:22,104 INFO [main] client. ...