Skip to content

An attempt to mimic the createFetcher API with React 16.2

Notifications You must be signed in to change notification settings

petegleeson/create-create-fetcher

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

8 Commits
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Create createFetcher

An attempt to mimic Suspense with React 16.2.

Why

For learning and programming gymnastics 🤸‍♂️

Usage

Do not really use this.

This example is lifted from ./src/starwars/character-list.js

const characterFetcher = createFetcher(page =>
  delay(1000)
    .then(() => fetch(`https://swapi.co/api/people/?page=${page}`))
    .then(resp => resp.json())
);

export const PaginatedCharacterList = () => (
  <DeferredState initialState={{ page: 1 }}>
    {({ page }, deferSetState) => {
      const { results, next, previous } = characterFetcher.read(page);
      return (
        <Fragment>
          <List characters={results} />
          <Pagination
            hasPrevious={previous}
            hasNext={next}
            onPrevious={() => deferSetState({ page: page - 1 })}
            onNext={() => deferSetState({ page: page + 1 })}
          />
        </Fragment>
      );
    }}
  </DeferredState>
);

Explaination

The DeferredState component handles async state changes. It holds state that is passed to a fetcher's read method.

The defaultState prop is used specify the initial async state.

The children of DeferredState is a function with two arguments. The first is the current state. The second is the deferSetState method. This method is used to change the state that DeferredState holds.

That's it 😃

About

An attempt to mimic the createFetcher API with React 16.2

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published