Skip to content
Permalink
Browse files

initial commit

  • Loading branch information...
jamesknelson committed Oct 25, 2019
0 parents commit 8545c990dc869fc4ec1fc00442bf930908b0c745
@@ -0,0 +1,3 @@
module.exports = {
extends: 'react-app',
}
@@ -0,0 +1,4 @@
*.log
.vscode
dist
node_modules
@@ -0,0 +1,11 @@
{
"useTabs": false,
"printWidth": 80,
"tabWidth": 2,
"singleQuote": true,
"trailingComma": "all",
"jsxBracketSameLine": true,
"parser": "typescript",
"semi": false,
"rcVerbose": false
}
20 LICENSE
@@ -0,0 +1,20 @@
Copyright 2019 James K Nelson

Permission is hereby granted, free of charge, to any person obtaining
a copy of this software and associated documentation files (the
'Software'), to deal in the Software without restriction, including
without limitation the rights to use, copy, modify, merge, publish,
distribute, sublicense, and/or sell copies of the Software, and to
permit persons to whom the Software is furnished to do so, subject to
the following conditions:

The above copyright notice and this permission notice shall be
included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED 'AS IS', WITHOUT WARRANTY OF ANY KIND,
EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
214 README.md
@@ -0,0 +1,214 @@
react-zen
=========

<a href="https://www.npmjs.com/package/react-zen"><img alt="NPM" src="https://img.shields.io/npm/v/react-zen.svg"></a>

**A collection of simple utilities for React**

```bash
yarn add react-zen
```

What?
-----

Currently, react-zen contains just two utilities:

- `createMirror(fetcher)`
- `useSnapshot(mirror, key)`

Together, these two functions let you easily consume asynchronous data in your React components. For example, here's how you'd load and display data from a REST API:

```js
import { Suspense } from 'react'
import { createMirror, useSnapshot } from 'react-zen'
// A mirror automatically fetches data as it is required, and purges it
// once it is no longer in use.
const api = createMirror(async url => {
let response = await fetch(BaseURL+url)
return response.json()
})
function Screen() {
// useSnapshot returns your data, loading status, etc.
let { data } = useSnapshot(api, '/todos/1')
return <div>{data.complete ? '✔️' : ''} {data.title}</div>
}
function App() {
return (
// Make sure to wrap your any component that use `useSnapshot()`
// with a <Suspense> tag.
<Suspense fallback={<div>Loading</div>}>
<Screen />
</Suspense>
)
}
```

Of course, you'll also want to be able to refresh and update your data. Mirrors and snapshots both have a suite of methods to make this easy. You can see how this works at the live example:

[See a full featured example at CodeSandbox]()



API
---

### `useSnapshot()`

Returns a snapshot of one key's data within a mirror.

```typescript
export function useSnapshot(
mirror: Mirror,
key: string,
): {
data: Data
key: Key
/**
* Set to true after `invalidate` has been called, and stays true until a
* more recent version of the document is received.
*/
invalidated: boolean
/**
* Indicates that a fetch is currently taking place.
*/
pending: boolean
/**
* Starts as false, and becomes true once `data` is set for the first time.
*/
primed: boolean
/**
* Marks this key's currently stored snapshot as invalid.
*
* If there's an active subscription, a new version of the data will be
* fetched.
*/
invalidate(): void
/**
* Stores the given data. If there is no subscription for it, then the data
* will be immediately scheduled for purge.
*
* In the case a function is given, if this key has a non-empty snapshot,
* then the updater callback will be called and the returned value will be
* set as the current data. If the key's snapshot is empty or is not yet
* primed, then an error will be thrown.
*
* This will not change the `pending` status of your data.
*/
update(dataOrUpdater: Data | MirrorUpdaterCallback): void
}
```


### `createMirror()`

Create a mirror of the data in some asynchronous source, where data is automatically fetched as required, and purged when no longer needed.

```typescript
createMirror(fetch: (
snapshot: Snapshot,
context: Context
) => Promise<Data>)
```


### `Mirror`

The object returned by `createMirror()`.

```typescript
interface Mirror {
/**
* Return a handle for the specified key, from which you can get
* and subscribe to its value.
*/
key(key: string): MirrorHandle
/**
* Return a list of the keys currently stored in the mirror for the given
* deps array.
*/
knownKeys(): Key[]
}
```


### `MirrorHandle`

As returned by `mirror.key(key)`

```typescript
interface MirrorHandle {
key: Key
/**
* Returns a promise to a mirrored snapshot for this key.
*/
get(): Promise<MirrorPrimedSnapshot<Data>>
/**
* Returns the latest snapshot for the given data if any exists, otherwise
* returns `null`.
*/
getLatest(): MirrorSnapshot<Data>
/**
* Subscribe to updates to snapshots for the given key. Note that this will
* not immediately emit a snapshot unless subscribing triggers a fetch, and
* adds/updates a snapshot in the process.
*/
subscribe(
callback: MirrorSubscribeCallback<Data, Key>,
): MirrorUnsubscribeFunction
/**
* Marks this key's currently stored snapshot as invalid.
*
* If there's an active subscription, a new version of the data will be
* fetched.
*/
invalidate(): void
/**
* Stores the given data. If there is no subscription for it, then the data
* will be immediately scheduled for purge.
*
* In the case a function is given, if this key has a non-empty snapshot,
* then the updater callback will be called and the returned value will be
* set as the current data. If the key's snapshot is empty or is not yet
* primed, then an error will be thrown.
*
* This will not change the `pending` status of your data.
*/
update(dataOrUpdater: Data | MirrorUpdaterCallback): void
}
```


Contributing / Plans
--------------------

A number of undocumented placeholder functions currently exist, which throw an exception when called. PRs implementing theses would be very welcome. Functions include:

- `mirror.keys()`, which should allow you to get/subscribe to a list of keys at once.
- `mirror.hydrateFromState()`, which should allow serialized data to be passed from the server to the client.
- `mirror.purge()`, which should allow all data within a mirror to be immediately purged.
- `handle.predictUpdate()`, which should allow for optimistic updates to be recorded against a key.

A number of *other* features have already been implemented, but need documentation and testing. These include namespaces and `extractState()`, both of which would be useful for server side rendering.

Finally, once `mirror.keys()` has been implemented, it should be possible to create a `CollectionMirror`, which allows you to subscribe to queries/collections as well as individual records.


License
-------

react-zen is MIT licensed.
@@ -0,0 +1,23 @@
# See https://help.github.com/articles/ignoring-files/ for more about ignoring files.

# dependencies
/node_modules
/.pnp
.pnp.js

# testing
/coverage

# production
/build

# misc
.DS_Store
.env.local
.env.development.local
.env.test.local
.env.production.local

npm-debug.log*
yarn-debug.log*
yarn-error.log*
@@ -0,0 +1,68 @@
This project was bootstrapped with [Create React App](https://github.com/facebook/create-react-app).

## Available Scripts

In the project directory, you can run:

### `yarn start`

Runs the app in the development mode.<br />
Open [http://localhost:3000](http://localhost:3000) to view it in the browser.

The page will reload if you make edits.<br />
You will also see any lint errors in the console.

### `yarn test`

Launches the test runner in the interactive watch mode.<br />
See the section about [running tests](https://facebook.github.io/create-react-app/docs/running-tests) for more information.

### `yarn build`

Builds the app for production to the `build` folder.<br />
It correctly bundles React in production mode and optimizes the build for the best performance.

The build is minified and the filenames include the hashes.<br />
Your app is ready to be deployed!

See the section about [deployment](https://facebook.github.io/create-react-app/docs/deployment) for more information.

### `yarn eject`

**Note: this is a one-way operation. Once you `eject`, you can’t go back!**

If you aren’t satisfied with the build tool and configuration choices, you can `eject` at any time. This command will remove the single build dependency from your project.

Instead, it will copy all the configuration files and the transitive dependencies (Webpack, Babel, ESLint, etc) right into your project so you have full control over them. All of the commands except `eject` will still work, but they will point to the copied scripts so you can tweak them. At this point you’re on your own.

You don’t have to ever use `eject`. The curated feature set is suitable for small and middle deployments, and you shouldn’t feel obligated to use this feature. However we understand that this tool wouldn’t be useful if you couldn’t customize it when you are ready for it.

## Learn More

You can learn more in the [Create React App documentation](https://facebook.github.io/create-react-app/docs/getting-started).

To learn React, check out the [React documentation](https://reactjs.org/).

### Code Splitting

This section has moved here: https://facebook.github.io/create-react-app/docs/code-splitting

### Analyzing the Bundle Size

This section has moved here: https://facebook.github.io/create-react-app/docs/analyzing-the-bundle-size

### Making a Progressive Web App

This section has moved here: https://facebook.github.io/create-react-app/docs/making-a-progressive-web-app

### Advanced Configuration

This section has moved here: https://facebook.github.io/create-react-app/docs/advanced-configuration

### Deployment

This section has moved here: https://facebook.github.io/create-react-app/docs/deployment

### `yarn build` fails to minify

This section has moved here: https://facebook.github.io/create-react-app/docs/troubleshooting#npm-run-build-fails-to-minify
@@ -0,0 +1,30 @@
{
"name": "todos",
"version": "0.1.0",
"private": true,
"dependencies": {
"react-scripts": "3.2.0",
"react-zen": "link:../.."
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
}
}
Binary file not shown.

0 comments on commit 8545c99

Please sign in to comment.
You can’t perform that action at this time.