react-sharedb
Run
ShareDB
inReact
What it does
- Brings real-time collaboration to React using ShareDB;
- Uses Racer to add a
model
to your app to do any data manipulations; - The
model
acts as a global singleton state, so you can use it as a replacement for other state-management systems likeRedux
orMobX
; - Makes the
render
reactive similar to how it's done inMobX
-- rerendering happens whenever anymodel
data you used inrender
changes.
use*()
[Hooks] observer(FunctionalComponent)
HOF
Higher Order Function which makes your functional component rendering reactive.
You have to wrap your functional components in it to be able to use react-sharedb
hooks.
{ let user $user = if !user return null // <Loading /> return <input value=username onChange= $user /> }
useDoc(collection, docId)
Refer to the documentation of subDoc()
below
useLocalDoc(collection, docId)
A convenience method to get the document you are already subscribed to
using the same API as useDoc()
let game $game = // It's the same as doing:let game $game =
useQuery(collection, query)
Refer to the documentation of subQuery()
below
useQueryIds(collection, ids, options)
Subscribe to documents in collection by their ids
collection
[String] -- collection name. Required
ids
[Array] -- array of strings which should be document ids.
options
[Object] --
js { reverse: false // reverse the order of resulting array }
Example:
useQueryDoc(collection, query)
Subscribe to a document using a query. It's the same as useDoc()
, but
with query
parameter instead of the particular docId
.
$limit: 1
and $sort: { createdAt: -1 }
are added to the query automatically (if they don't already exist).
collection
[String] -- collection name. Required
query
[Object] -- query object, same as in useQuery()
.
Example:
useLocal(path)
Refer to the documentation of subLocal()
below
useSession(path)
A convenience method to access the _session
local collection.
let userId $userId = // It's the same as doing:let userId $userId =
usePage(path)
A convenience method to access the _page
local collection.
let game $game = // It's the same as doing:let game $game =
useValue(value)
Refer to the documentation of subValue()
below
useModel(path)
Return a model scoped to path
(memoized by the path
argument).
If path
is not provided, returns the model scoped to the root path.
const Main = const Content = const Sidebar =
[Hooks] Example
{ let secret $secret = let userId $userId = let user $user = let game $game = if !game && user return null // <Loading /> let players $players = if !players return null // <Loading /> let users $users = if !users return null // <Loading /> { $secret } { $user } return <div> <label> Secret: <input type='text' value=code onChange=updateSecret /> </label> <label> My User Name: <input type='text' value=username onChange=updateName /> </label> <h1>Game gametitle</h1> <h2>Users in game:</h2> <p>users</p> </div> }
TODO:
useSubscribe(fns)
<Suspense />
support
@subscribe(cb)
[Classes] HOC @subscribe
decorator is used to specify what you want to subscribe to.
@subscribe
gives react component a personal local scope model, located at path $components.<random_id>
.
This model will be automatically cleared when the component is unmounted.
HOW TO: Subscribe to data and use it in render()
@subscribe
accepts a single argument -- cb
, which receives props
and must return the subscriptions object
.
Each key
in the subscriptions object
will fetch specified data from the MongoDB or a Local path and
will write it into the component's personal scope model under that key
.
The read-only data of the component's model is available as this.props.store
.
Use it to render the data you subscribed to, same way you would use this.state
.
IMPORTANT As with this.state
, the this.props.store
SHOULD NOT be modified directly! Read below to find out how to modify data.
Example:
@@Component { let room myUser usersInRoom = thispropsstore return <Fragment> <h1>roomname</h1> <h2>Me: myUsername</h2> <p>Other users in the room: usersInRoom</p> </Fragment> }
As seen from the example, you can combine multiple @subscribe
one after another.
HOW TO: Modify the data you subscribed to
The actual scoped model of the component is available as this.props.$store
.
Use it to modify the data. For the API to modify stuff refer to the Racer documentation
In addition, all things from subscriptions object
you subscribed to are
available to you as additional scope models in this.props
under names this.props.$KEY
Example:
@Component { let $store $room = thisprops $room // You can also use $store to do the same: $store } { let room = thispropsstore return <Fragment> <h1>roomname</h1> <button onClick=thisupdateName>Update Name</button> </Fragment> }
sub*()
functions
[Classes] Use sub*() functions to define a particular subscription.
subDoc(collection, docId)
Subscribe to a particular document.
You'll receive the document data as props.store.{key}
collection
[String] -- collection name. Required
docId
[String] -- document id. Required
Example:
@
subQuery(collection, query)
Subscribe to the Mongo query.
You'll receive the docuents as an array: props.store.{key}
You'll also receive an array of ids of those documents as props.store.{key}Ids
collection
[String] -- collection name. Required
query
[Object] -- query (regular, $count
, $aggregate
queries are supported). Required
Example:
@
IMPORTANT: The scope model ${key}
, which you receive from subscription, targets
an the array in the local model of the component, NOT the global collection
path.
So you won't be able to use it to efficiently update document's data. Instead you should manually
create a scope model which targets a particular document, using the id:
let usersInRoom $store = thispropsstorefor let user of usersInRoom $storescope`.`
subLocal(path)
Subscribe to the data you already have in your local model by path.
You'll receive the data on that path as props.store.{key}
You will usually use it to subscribe to private collections like _page
or _session
.
This is very useful when you want to share the state between multiple components.
It's also possible to subscribe to the path from a public collection, for example when you want to work with some nested value of a particular document you have already subscribed to.
Example:
const TopBar = $sidebarOpened <button onClick= $sidebarOpened >Open Sidebar</button> const Sidebar = store: sidebarOpened sidebarOpened ? <p>Sidebar</p> : null
subValue(value)
A constant value to assign to the local scoped model of the component.
value
[String] -- value to assign (any type)
[Classes] Example
Below is an example of a simple app with 2 components:
Home
-- sets up my userId and rendersRoom
Room
-- shows my user name ands lets user update it, shows all users which are currently in the room.
// Home.jsx // `subscribe` means that the data is reactive and gets dynamically updated// whenever the data in MongoDB or in private collections gets updated. @ Component { super...props // For each thing you subscribe to, you receive a scoped `model` // with the same name prefixed with `$` in `props`. Use it // to update the data with the `model` operations available in Racer: // https://derbyjs.com/docs/derby-0.10/models let $userId = thisprops // Update the private path `_session.userId` with the new value // // We'll use this `_session.userId` in all other children // components to easily get the userId without doing the potentially // heavy/long process of fetching the userId over and over again. $userId } // Get my userId somehow (for example from the server-side response). // For simplicity, we'll just generate a random guid in this example // by creating an empty user document each time, so whenever // you open a new page, you'll be a new user. model <Room roomId='myCoolRoom1' />
// Room.jsx @ // All things you subscribe to end up in `props.store` under the same name.// We can do a second subscribe using the data we received in the first one. @ // Additionally, whenever you subscribe to the MongoDB query, you also// receive the `Ids` in store.// For example, subscribing to the `users` collection above populated// `props.store.users` (array of documents) AND// `props.store.userIds` (array of ids) - auto singular name with the `Ids` suffix Component { super...props let $room roomId = thisprops let userId room room: userIds = = thispropsstore // Create an empty room if it wasn't created yet if !room model // Add user to the room unless he's already there if !userIds $room } { let $myUser = thisprops $myUser } { let myUser room users userId = thispropsstore return <main> <h1>roomtitle</h1> <section> My User Name: <input type='text' value=myUsername onChange=thischangeName /> </section> <h3>Users in the room:</h3> users // exclude my user </main> }
Licence
MIT
(c) Decision Mapper - http://decisionmapper.com