Package Exports
- @gdo-bzh/suspense-utils
This package does not declare an exports field, so the exports above have been automatically detected and optimized by JSPM instead. If any package subpath is missing, it is recommended to post an issue to the original package (@gdo-bzh/suspense-utils) to support the "exports" field. If that is not possible, create a JSPM override to customize the exports field for this package.
Readme
suspense-utils
the package contains: createResource(): a method to create a resource. A resource is anything we could fetch and cache.
Install
yarn add @gdo-bzh/suspense-utils react
Usage
import React from 'react'
import styled from '@xstyled/styled-components'
import { createResource, Resource } from '@gdo-bzh/suspense-utils'
import { ErrorBoundary } from '@gdo-bzh/error-boundary'
import { CircleDots } from '@gdo-bzh/spinner'
type Post = {
userId: number
id: number
title: string
body: string
}
let resource: Resource<Post[]>
const fetchPosts = () =>
fetch(`https://jsonplaceholder.typicode.com/posts`).then(response => response.json())
const Layout = styled.div`
position: relative;
display: flex;
justify-content: center;
`
const PostsList = styled.ul`
list-style: none;
`
const Post: React.FC<Post> = ({ title, body }) => (
<li>
<h2>{title}</h2>
<div>{body}</div>
</li>
)
const Posts: React.FC = () => {
if (!resource) {
resource = createResource<Post[]>(fetchPosts)
}
return (
<PostsList>
{resource
.read()
.slice(0, 10)
.map(post => (
<Post {...post} />
))}
</PostsList>
)
}
export const Example: React.FC = () => {
return (
<Layout>
<ErrorBoundary Fallback={({ error }) => <div>{error.message}</div>}>
<Suspense fallback={<CircleDots size="30px" />}>
<Posts />
</Suspense>
</ErrorBoundary>
</Layout>
)
}
Types
type Resource<T> = {
read: () => T
}
type CreateResource<T> = (
asyncFunc: (extraData?: Data) => Promise<T>,
extraData?: Data
) => Resource<T>
License
MIT © gdo-bzh