HzQL
Data Fetching for React Using Horizon 2
npm install --save hzql
- Easy bindings from Horizon into React
- Support for Horizon 2
- Support for server side rendering
HzQL with React colocates your data and components. It requires Horizon 2
for its new hz.model
query.
Example
const horizon = @ { if !thispropsusers || !thispropsposts return <span>Loading...</span> return <div> <h1>Users:</h1> thispropsusers <h1>Posts:</h1> thispropsposts </div> }
Setting up HzQL
HzQL exports a Provider
component to wrap your app in.
Any component using a query must be a child of Provider
Example
let horizon = let <Provider horizon=horizon> <App /> </Provider>
Writing Queries
Queries are a function of the form hz => props => query
. A query can use the
props from the parent component to write the query. The exported connect
function wires up a query to a component. The keys of the query will be passed
as props to the immediate child
Example
const App = <pre>Users: <pre>Users: propsusers</pre>propsusers</pre> const query = users: queryApp
To run a live query, use connect.live
instead of connect
Using the new decorator syntax:
@connect { return <pre>Users: thispropsusers</pre> }
Waiting for Results
If you would prefer for the component to not render at all until the results
of the query arrive, you can use connect.await
. This will cause your
component to always return null
from render
until the query is finished.
The watching equivalent of this is connect.liveAwait
Example
const App = <pre>Users: thispropsusers</pre> const query = users: // This will render to `null` until `hz('posts').order('date')` is retrievedApp
Mutations
The horizon instance is passed down to child components, which can perform mutations.
Example
{ superprops thisstate = input: '' thishandleInput = thishandleInput thishandleSubmit = thishandleSubmit } { this } { thisprops } { return <div> <input onChange=thishandleInput value=thisstateinput /> <button onClick=thishandleSubmit>Submit</button> </div> } App {}
Server side rendering
To render on the server, install node-fibers
using
npm i -S node-fibers
In your server code, your call to renderToString
should look something like
// Give Horizon a websocket library to useglobalWebSocket = wsconst app = app app