redux

Subspace can be used with redux. Subspace returns Observables, which you can subscribe to, and if this subscription has access to the redux store, it will be able to dispatch actions when the observable emits an event.

Example

Here's a simple example on how to setup Subspace to work with redux:

This example is available in Github

index.js

import store from './store';
import web3 from './web3';
import Subspace from '@status-im/subspace';
import { myAction } from './actions';

const run = async () => {
  const MyContractInstance = ...; // TODO: obtain a web3.eth.contract instance

  const subspace = new Subspace("ws://localhost:8545"); // Use a valid websocket provider (geth, parity, infura...)
  await subspace.init();
    
  subspace.trackEvent(MyContractInstance, "MyEvent", {filter: {}, fromBlock: 1 })
             .subscribe(eventData => {
               store.dispatch(myAction(eventData));
             });
}

run();
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18

Handling Contract Objects

The variable MyContractInstance is a web3.eth.Contract object pointing to a deployed contract address. You can use a DApp framework like Embark to easily import that contract instance: import { MyContract } from './embarkArtifacts/contracts';, or use web3.js directly (just like in the example source code)

store.js

import { createStore } from 'redux';
import {myReducer} from './reducer';

export default store = createStore(myReducer);
1
2
3
4

reducer.js

import { MY_ACTION } from "./constants";

const initialState = { 
  data: {}
};

export const myReducer = (state = initialState, action) => {
  switch (action.type) {
    case MY_ACTION:
      return { data: action.eventData };
    default:
      return state;
  }
};
1
2
3
4
5
6
7
8
9
10
11
12
13
14

constants.js

export const MY_ACTION = 'MY_ACTION';
1

actions.js

import {MY_ACTION} from './constants.js';

export const myAction = eventData => ({type: MY_ACTION, eventData});
1
2
3

Using React and Redux

A practical example can also be found in examples/react-redux.