subspace-docs/react.md

77 lines
1.9 KiB
Markdown
Raw Normal View History

# React
We provide a higher-order component to connect to enhance presentational components to react to any observable (not limited to those generated by Phoenix).
2019-09-03 14:40:19 -04:00
### Usage
```js
import { observe } from 'phoenix/react';
const ObserverComponent = observe(WrappedComponent);
```
This enhanced component will subscribe to any observable property it receives when the component is mounted and automatically unsubscribe when the component is unmounted.
### Example
#### MyComponentObserver.js
2019-09-03 14:40:19 -04:00
```js
import React from "react";
import ReactDOM from 'react-dom';
import {observe} from "phoenix/react";
const MyComponent = ({eventData}) => {
// Handle initial state when no data is available
if (!eventData) {
2019-09-03 14:40:19 -04:00
return <p>Loading...</p>;
}
2019-09-03 14:40:19 -04:00
return <p>{eventData.someReturnedValue}</p>
};
// MyComponent will now observe any observable prop it receives
// and update its state whenever the observable emits an event
export default observe(MyComponent);
```
2019-09-03 14:40:19 -04:00
#### App.js
```js
/* global web3 */
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import Phoenix from 'phoenix';
import MyComponentObserver from './MyComponentObserver';
2019-09-03 14:40:19 -04:00
// This is a web3.eth.Contract object
import SimpleStorageContract from "./SimpleStorageContract";
class App extends Component {
2019-09-03 14:40:19 -04:00
state = {
myEventObservable$: null
2019-09-03 14:40:19 -04:00
}
componentDidMount() {
const eventSyncer = new Phoenix(web3.currentProvider);
eventSyncer.init()
.then(
const myEventObservable$ = eventSyncer.trackEvent(SimpleStorageContract, "MyEvent", {}, fromBlock: 1 });
this.setState({ myEventObservable$ });
2019-09-03 14:40:19 -04:00
);
}
render() {
return <MyComponentObserver eventData={this.state.myEventObservable$} />;
2019-09-03 14:40:19 -04:00
}
}
export default App;
2019-09-03 14:40:19 -04:00
```
#### index.js
```js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));
```