mirror of
https://github.com/status-im/subspace-docs.git
synced 2025-02-01 15:37:46 +00:00
1.9 KiB
1.9 KiB
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).
Usage
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
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) {
return <p>Loading...</p>;
}
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);
App.js
/* global web3 */
import React, {Component} from 'react';
import ReactDOM from 'react-dom';
import Phoenix from 'phoenix';
import MyComponentObserver from './MyComponentObserver';
// This is a web3.eth.Contract object
import SimpleStorageContract from "./SimpleStorageContract";
class App extends Component {
state = {
myEventObservable$: null
}
componentDidMount() {
const eventSyncer = new Phoenix(web3.currentProvider);
eventSyncer.init()
.then(
const myEventObservable$ = eventSyncer.trackEvent(SimpleStorageContract, "MyEvent", {}, fromBlock: 1 });
this.setState({ myEventObservable$ });
);
}
render() {
return <MyComponentObserver eventData={this.state.myEventObservable$} />;
}
}
export default App;
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
ReactDOM.render(<App />, document.getElementById('root'));