How to use react-cache - 10 common examples

To help you get started, we’ve selected a few react-cache examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github jaredpalmer / react-conf-2018 / full-suspense / src / components / HomePage.js View on Github external
import React from 'react';
import ListItem from './ListItem';
import { fetchArtistListJSON } from '../api';
import { Logo } from './Icon/Logo';
import { unstable_createResource } from 'react-cache';
import { Spinner } from './Spinner';

const ArttistListResource = unstable_createResource(fetchArtistListJSON);

class Search extends React.Component {
  state = {
    // toggles whether to show or hide the inline loading spinner
    // just like native iOS!
    currentId: null,
  };

  render() {
    return (
      <div className="search">
        <Logo />
        <React.Suspense maxDuration={1000} fallback={<Spinner size="large" />}>
          {ArttistListResource.read().map(item => (
            <ListItem
              to={`/artist/${item.id}`}
github topheman / react-fiber-experiments / src / containers / SuspenseCoursesContainer.js View on Github external
* Network failure handling - I've tried:
 * - ErrorBoundaries: The first error thrown by the api promise is catched but the ones
 * thrown after by react-cache due to cache miss after trying to remount the node
 * finally bring down the app.
 *
 * For the moment, when I createResource, I return a function that swallows its own errors
 * (by returning promise.catch()) and if an error has occured, the resolved object will
 * contain a attribute "error" with a truthy value.
 *
 * This value is then checked at rendering to choose whether to render data or error.
 */
const CourseResource = createResource(courseId =>
  fakeApi(`/course/${courseId}`).catch(error => ({ error }))
);

const NextLessonResource = createResource(courseId =>
  fakeApi(`/course/${courseId}/nextLesson`).catch(error => ({ error }))
);

const Course = ({ courseId, delayMs, ...remainingProps }) => {
  NextLessonResource.preload(courseId); // avoid serial requests
  const courseData = CourseResource.read(courseId);
  return courseData && !courseData.error ? (
    <div {...remainingProps}>
      <CourseInfos data-testid="course-infos" data={courseData} />
      <Suspense
        maxDuration={parseInt(delayMs, 10)}
        fallback={<Spinner data-testid="next-lesson-spinner" />}
      >
        <NextLesson data-testid="next-lesson" courseId={courseId} />
      </Suspense>
      <div>
github jaredpalmer / react-conf-2018 / src / suspense / Artist.js View on Github external
import React from 'react';
import { fetch } from '../fetch';
import { createResource } from 'react-cache';
import { cache } from '../cache';
import { Spinner } from '../components/Spinner';
import { Img } from './Img';
const ArtistTopTracks = React.lazy(() => import('./ArtistTopTracks'));
// const ArtistAlbums = React.lazy(() => import('./ArtistAlbums'));
const ArtistRelatedArtists = React.lazy(() => import('./ArtistRelatedArtists'));

const ArtistResource = createResource(id =>
  fetch(`https://api.spotify.com/v1/artists/${id}`)
    .then(res => res.json())
    .then(
      artist => artist,
      error => {
        throw new Error(error);
      }
    )
);

function ArtistHeading(props) {
  const artist = ArtistResource.read(cache, props.id);
  return (
    <div className="heading">
      {artist.images &&
      artist.images.length > 0 &&
github topheman / react-fiber-experiments / src / cache.js View on Github external
export function initCache() {
  // `createCache` accepts an invalidator function in first argument: https://github.com/facebook/react/blob/master/packages/react-cache/src/ReactCache.js#L152
  cache = createCache(initCache);
}
github andrewiggins / react-suspense-sandbox / src / suspense / index.jsx View on Github external
import * as React from "react";
import * as ReactDOM from "react-dom";
import { unstable_createResource as createResource } from "react-cache";
import { unstable_scheduleCallback } from "scheduler";
import { getText } from "./getText";

const readText = createResource(getText);

function Text({ value }) {
  return <span>{value}</span>;
}

function AsyncText({ value }) {
  value = readText.read(value);
  return <Text value={value} />;
}

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      value: 0,
      valueAsync: 0
github koba04 / react-hacker-news-stories / src / hackerNewsResource.ts View on Github external
import { unstable_createResource as createResource } from "react-cache";

import {
  fetchHackerNews,
  fetchHackerNewsComments,
  Story,
  Comment
} from "./hackerNews";

export const storiesResource = createResource<number, Story[]>(fetchHackerNews);

export const commentsResource = createResource<number[], Comment[]>(
  fetchHackerNewsComments,
  ids => ids.sort().join()
);
github psychobolt / react-pie-menu / stories / UserPage / UserPage.component.js View on Github external
import './styles.css';
import React, { Suspense } from 'react';
import { unstable_createResource as createResource } from 'react-cache';
import styled from 'styled-components';

import { fetchContributors } from './api';
import Details from './Details';
import Spinner, { SIZES } from './Spinner';
import * as styles from './UserPage.style';

const UserDetailsResource = createResource(fetchContributors);

const Container = styled.div`${styles.container}`;

const Repositories = React.lazy(() => import('./Repositories'));

const Contributors = () => {
  const users = UserDetailsResource.read();
  return users.map(user => (
    <Container key={user.name}>
      <Details image={user.image} name={user.name} />
      <Suspense fallback={<Spinner size={SIZES.Medium} />}>
        <Repositories id={user.name} />
      </Suspense>
    </Container>
  ));
};
github msd-code-academy / react-workshop / 04-suspense-and-async-mode / exercise / src / pages / kitties.jsx View on Github external
import React, {Suspense} from 'react';
import {unstable_createResource as createResource} from 'react-cache';
import './kitties.css';

const catApiResource = createResource(async() => {
  const response = await fetch('https://api.thecatapi.com/v1/images/search');
  const [result] = await response.json();
  const img = new Image();
  const src = await new Promise(resolve => {
    img.onload = () => resolve(result.url);
    img.src = result.url;
  });
  return src;
});

const KittyImage = ({ID}) => {
  const url = catApiResource.read(ID);
  return <img src={url} alt="randomKitty" className="kitty-image" />;
};

export default class Kitties extends React.Component {
github facebook / react / fixtures / unstable-async / suspense / src / components / UserPage.js View on Github external
<svg
      viewBox="0 0 24 24"
      style={{
        width: '24px',
        height: '24px',
        marginRight: '0.5rem',
        fill: 'currentColor',
      }}>
      <path d="M20 4H4c-1.1 0-1.99.9-1.99 2L2 18c0 1.1.9 2 2 2h16c1.1 0 2-.9 2-2V6c0-1.1-.9-2-2-2zm0 4l-8 5-8-5V6l8 5 8-5v2z" />
      <path d="M0 0h24v24H0z" fill="none" />
    </svg>
    <a href={`mailto:${email}`}>{email}</a>
  </div>
);

const ImageResource = unstable_createResource(
  src =>
    new Promise(resolve => {
      const img = new Image();
      img.onload = () => resolve(src);
      img.src = src;
    })
);

function Img({src, alt, ...rest}) {
  return <img src={ImageResource.read(src)} alt={alt} {...rest} />;
}

function UserPicture({source}) {
  return (
    <Suspense maxDuration={1500} fallback={<img src={source} alt="poster" />}>
      <Img
github BenoitZugmeyer / react-suspense-demo / src / components / MoviePage.js View on Github external
import React, { Suspense } from "react";
import { unstable_createResource as createResource } from "react-cache";
import { fetchMovieDetails, fetchMovieReviews } from "../api";
import Icon from "./Icon";
import Spinner from "./Spinner";
import "./MoviePage.css";

const movieDetailsFetcher = createResource(fetchMovieDetails);
const movieReviewsFetcher = createResource(fetchMovieReviews);

function Rating({ label, score, icon }) {
  if (typeof score !== "number" || score < 0) return null;
  return (
    <div className="Rating">
      <div className="small-title">{label}</div>
      {icon && (
        <div>
          <Icon type={icon} size="medium" />
        </div>
      )}
      <div className="rating-score">{score}%</div>
    </div>
  );
}

react-cache

A basic cache for React applications

MIT
Latest version published 4 years ago

Package Health Score

75 / 100
Full package analysis

Similar packages