Giter VIP home page Giter VIP logo

tipple's Introduction

Tipple logo

Tipple

A lightweight dependency-free library for fetching data over REST in React.

Gitlab pipeline status coverage version size licence

What is Tipple?

Tipple is simple - so simple in fact, it has no dependencies.

If you're working with REST and want an easy way to manage data fetching on the client side, this might just be the way to go.

How does it work?

There's two key parts to Tipple:

  1. Request state management - a fancy way of saying Tipple will manage the numerous states of your API calls so you don't have to.
  2. Domain based integrity - because each request is tied to a domain (e.g. users, posts, comments), Tipple can force data to be re-fetched whenever domain(s) have been mutated.

Getting started

Install tipple

I'm sure you've done this before

npm i tipple

Configure the context

Tipple exposes the client using React's context. You'll want to put the provider in the root of your project in order to use the useFetch and usePush hooks.

import { createClient, TippleProvider } from 'tipple';
import { AppContent } from './AppContent';

const client = createClient({ baseUrl: 'http://localhost:1234/api' });

export const App = () => (
  <TippleProvider client={client}>
    <AppContent />
  </TippleProvider>
);

Start requesting

The useFetch hook will fetch the data you need on mount

import { useFetch } from 'tipple';

interface User {
  id: number;
  name: string;
}

const MyComponent = () => {
  const [state, refetch] = useFetch<User[]>('/', { domains: ['users'] });
  const { fetching, error, data } = state;

  if (fetching && data === undefined) {
    return <p>Fetching</p>;
  }

  if (error || data === undefined) {
    return <p>Something went wrong</p>;
  }

  return (
    <>
      {data.map(user => (
        <h2 key={user.id}>{user.name}</h2>
      ))}
      <button onClick={refetch}>Refetch</button>
    </>
  );
};

Further documentation

For more advanced usage, check out the docs.

There's also an example project if you're into that kind of thing.

tipple's People

Contributors

andyrichardson avatar flgmwt avatar kadikraman avatar kitten avatar simonxabris avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

tipple's Issues

Add ability to add custom reducers/handlers

This adds the option for teams to specify custom reducer logic to manually update the data store and 'shouldRefetch' states.

This is an optional extra and the current implementation will work in an identical fashion without the need for custom reducers.

Prevent duplicate fetch requests

useQuery requests should be deduped.

This needs to be implemented in the executeRequest function using the URL as a key and returning existing promises that are in flight.

Any beginners who aren't sure where to start, leave a comment and we can run through this together or pair.

Add "new Suspense" support

https://reactjs.org/docs/concurrent-mode-suspense.html

Update 1

Quick update on my thoughts surrounding this so far.

While there isn't a huge amount of work to support concurrent-react, there are pattern changes that will need to be considered.

I haven't used these patterns in person yet so I will save my scepticism until having tried it out. The following API changes would need to be made:

  • useFetch / usePush would need to stay the same (breaking changes would occur otherwise)
  • usePreloadedFetch / usePreloadedPush would be completely separate implementations which are responsible for reading from the client and throwing / resolving results
  • preloadFetch / preloadPush would be responsible for triggering API calls

This has two major impacts on Tipple:

  • For suspense support, fetching + reading state are two separate interactions (as opposed to useXYZ which does both)
  • As fetching in Tipple is currently coupled to the hooks/calling components, changes would need to be made to the client + overall implementation

Parse data on receipt

Add option in useFetch / usePush to parse response data.

This parsing will only be used in the client's stateful representation of the data. It should not change the state of the data going into the cache.

ability to change client fetchOptions dynamically

Let's say you set an Authorization header based on a token stored in local storage

const token = getToken();

const headers = { "content-type": "application/json" };
if (token) {
  headers.Authorization = `Bearer ${token}`;
}

const client = createClient({
  baseUrl: 'x',
  fetchOptions: {
    headers
  }
});

Now if I change or delete the token stored in local storage the client won't be updated with the new token.
Maybe if the lib provided a function to change fetchOptions, something like apollo client does, would solve this case.

Improve test coverage

Test coverage is currently around 96%. Adding a few more test cases to improve overall coverage would be valuable.

Gaps in coverage can be found by clicking the coverage badge in the README.

Add option to not auto-fetch on mount

Currently, a fetch is triggered on-mount for network enabled fetches (e.g. non cache-only policies).

The proposal is to allow disabling of this functionality so that fetches can be delayed until a manual trigger.

This will affect the following cache policies:

  • cache-first - data will be retrieved from cache but the API call will not be triggered until a manual refetch call is made
  • network-first - no request will be made until the manual refetch call is made

Add caching policies

Add cache policies for useFetch such as "cache only", "cache and network", etc.

Add ability to specify fetchOptions on fetch & push execution

Overview

There will inevitably be edge cases where a mutation needs to be triggered immediately following a state change.

Note: Most of the time, this shouldn't be the case as state change events should ideally be separate from submission events.

This could be problematic as the change in state may not be applied until a later render.

Proposal

Add argument to executeRequest which allows fetchOptions to be specified.

Example button click handler

const newVal = value + 10;

setValue(newVal) // Update state
executeRequest({ body: JSON.stringify(newVal) }); // Immediately make api call

Make createClient arg optional

Create client argument is not required. Typescript types need to be updated.

Note: This is particularly useful for using createClient during testing.

Domains -> Resource

This is cool πŸ‘πŸ‘πŸ‘

In keeping with RESTful terminology for the primary data representation would you consider renaming the references to domain to resource? Additionally domain has a specific meaning when dealing with URLs which might be confusing.

Prepare for v0.4 relase

  • Make changelog
  • Update README examples
  • Update docs examples
  • Add client + testing sections to docs

Add persistence capability to the client

Some users (particularly native) will want to persist the cache between reloads/restarts of their app.

For browsers, this will be a pretty easy use of localStorage. As for native, that needs to be looked into.

Separate client logic from Provider

There are a bunch of benefits to storing the client outside of the provider and passing it in as an argument:

  • Client can be used without react
  • Allow for external invalidation - clearDomains my need to be called for use cases outside of a push (such as on incoming websocket information)
  • Seperation of concerns
  • Easier testing

Paginating Resource

I Really Love This Tipple Idea And I Just Tried It Out And It’s Wow.

But I’ve Been Wondering How I’d Deal With A Paginated Resources List

Add displayName attribute to components

Components (Provider) do not have a displayName attribute.

It would be nice to be able to do this while still using anonymous functions. Ideally there would be capability within the current build toolchain.

Add network-only cache policy

For one time network requests (use cases such as security related requests).

This will not write or read from the cache and cannot be allocated to a domain.

Allow non-json responses

Some responses such as a DELETE could have no content type.

This should be checked before trying to parse JSON.

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    πŸ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. πŸ“ŠπŸ“ˆπŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❀️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.