https://github.com/mdebbar/mobx-cache
An observable data cache with MobX
https://github.com/mdebbar/mobx-cache
Last synced: about 2 months ago
JSON representation
An observable data cache with MobX
- Host: GitHub
- URL: https://github.com/mdebbar/mobx-cache
- Owner: mdebbar
- License: unlicense
- Created: 2016-09-09T06:41:39.000Z (over 8 years ago)
- Default Branch: master
- Last Pushed: 2016-09-13T17:15:21.000Z (over 8 years ago)
- Last Synced: 2025-04-13T08:06:23.569Z (about 2 months ago)
- Language: JavaScript
- Size: 16.6 KB
- Stars: 26
- Watchers: 3
- Forks: 1
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# MobxCache
_An observable data cache with [MobX](https://mobxjs.github.io/mobx/)._[](https://travis-ci.org/mdebbar/mobx-cache)
[](https://coveralls.io/github/mdebbar/mobx-cache?branch=master)
[](https://www.npmjs.com/package/mobx-cache)## Installation
If using npm to manage your dependencies, you can easily do:
```
npm install --save mobx-cache
```
Also, make sure `mobx` is installed since this library relies on it.## Example 1: Simple hello world
```javascript
import React from "react"
import MobxCache from "mobx-cache"
import { observer } from "mobx-react"var helloMessages = new MobxCache((name) => `Hello, ${name}`)
const HelloWorldApp = observer(function HelloWorldApp(props) {
return (
{helloMessages.get(props.name).value}
)
})React.render(, document.body)
// The next line will update the cache and cause `HelloWorldApp` to re-render
// with the new message:
helloMessages.populate('John Doe', 'Hello again, John!')
```The above example is for demonstration purposes only. It may not be useful in real life. This library is especially useful when used for data fetching as the next example shows.
## Example 2: User profile
```javascript
import React from "react"
import MobxCache from "mobx-cache"
import { observer } from "mobx-react"var usersCache = new MobxCache((id) => fetch(`/users/${id}`))
const UserProfile = observer(function HelloWorldApp(props) {
const entry = usersCache.get(props.id)
if (entry.status !== 'success') {
returnLoading...
}const user = entry.value
return (
![]()
{user.name}
{user.bio}
)
})// Rendering with the id 199 will cause the fetching of user 199.
React.render(, document.body)// When we render with a different id, the new user will be fetched and rendered.
React.render(, document.body)
```
The `fetch` function can be any function that sends a request to the given url and returns a promise. The promise will automatically be handlded by MobxCache.