use-optimistic-mutation
TypeScript icon, indicating that this package has built-in type declarations

0.2.3 • Public • Published

use-optimistic-mutation

NPM JavaScript Style Guide

Install

npm install --save use-optimistic-mutation

Usage

import * as React from 'react';
import * as ReactDOM from 'react-dom';
import { useQuery } from 'react-query';
import useOptimisticMutation from '../.';

interface IUser {
  name: string;
}

let USER_DB_MOCK: IUser = { name: 'Lisa' };

function getUser(): Promise<IUser> {
  return new Promise(resolve =>
    setTimeout(() => {
      resolve(USER_DB_MOCK);
    }, 1000)
  );
}

function updateUser(user: IUser): Promise<IUser> {
  return new Promise((resolve, reject) => {
    setTimeout(() => {
      USER_DB_MOCK = user;
      return resolve(USER_DB_MOCK);
    }, 1000);
  });
}

const App = () => {
  const { data, status } = useQuery(['user'], getUser);
  const [update] = useOptimisticMutation(['user'], updateUser);

  if (status === 'loading') {
    return <h5>Fetching name…</h5>;
  }

  if (data === undefined) {
    return <h5>No user received</h5>;
  }

  return (
    <div>
      <h4>Name: {data.name}</h4>
      <button onClick={() => update({ name: 'Marge' })}>
        Update name optimisticly
      </button>
    </div>
  );
};

License

MIT © FrimJo

Dependencies (0)

    Dev Dependencies (12)

    Package Sidebar

    Install

    npm i use-optimistic-mutation

    Weekly Downloads

    3

    Version

    0.2.3

    License

    MIT

    Unpacked Size

    22.3 kB

    Total Files

    15

    Last publish

    Collaborators

    • frimjo