What is the best way to use response-redux with an event-based third-party library

What is the best way to connect a view to a library that constantly sends events? I saw in a real redux example that it is best to use mapDispatchToProps and introduce a load action. In our case, we need to listen to events for sending over time. I thought we could use middleware for this, but I'm not 100% sure. Another alternative would be to listen inside the creator of the action itself.

Any ideas?

//app.jsx

<div>
  <MyCollection name="ONE" />
  <MyCollection name="TWO" />
</div>

//my-collection.jsx

import {load} from './actions';

class MyCollection extends React.Component {
  componentDidMount() {
    this.props.load(this.props.name);
  }

  componentDidUpdate(prevProps) {
    if(prevProps.name !== this.props.name) {
      this.props.load(this.props.name);
    }
  }

  render() {
    return (
      <div>{this.props.name}: {this.props.value}</div>
    )
  }
}

function mapStateToProps(state) {
  return {
    value: state.value
  }
}

const mapDispatchToProps = {
  loadAndWatch
}

connect(mapStateToProps, mapDispatchToProps)(MyCollection);

//actions.js

import {MyCollection} from '@corp/library';

export function load(name) {
  return (dispatch, getState) => {
    MyCollection.getValue(name, value => {
      dispatch(setValue(name));
    })
  }
}

export function setValue(name) {
  return {
    type: 'SET_VALUE',
    name
  }
}

//reducer.js

function reducer(state, action) {
  switch(action.type) {
    case 'SET_WATCHING':
      return Object.assign({}, state, {isWatching: true});
    case 'SET_VALUE':
      return Object.assign({}, state, {value: action.value});
    default:
      return state;
  }
}

//middleware.js

import {setValue} from './actions';

function middleware({dispatch, getState}) {
  return next => action => {
    switch (action.type) {
      case 'SET_VALUE':
        next(action);

        if (getState().isWatching) {
          return;
        }

        MyCollection.addChangeListener(name, value => {
          dispatch(setValue(name))
        });

        dispatch({type: 'SET_WATCHING'});    
    }
  }
}
+4
source share
1

, redux-observable - , , , .

0

All Articles