frintjs / frint

Modular JavaScript framework for building scalable and reactive applications
https://frint.js.org/
MIT License
755 stars 34 forks source link

Proposal: frint-redux #359

Closed fahad19 closed 6 years ago

fahad19 commented 7 years ago

(Intended to be done in a separate repository)

What

Integration of Redux with FrintJS

Proposed API

Package: frint-redux

import { createStore } from 'redux';
import { getState$ } from 'frint-redux';

const store = createStore(someRootReducer);

const state$ = getState$(store);

The getState$() function should accept store, and return the state as an Observable.

Implementation can look something like this:

import { Observable } from 'rxjs/Observable';

function getState$(store) {
  return new Observable(function (observer) {
    observer.next(store.getState());

    const cancelListener = store.subscribe(function () {
      observer.next(store.getState());
    });

    return function unsubscribe() {
      cancelListener();
    };
  });
}

Package: frint-redux-react

Should export a connect higher-order Component similar to one from react-redux. Instead of requiring any <Provider /> component, it will access the store by doing app.get('store'):

import React from 'react';
import { connect } from 'frint-redux-react';

function MyComponent(props) {
  const { todos } = props;

  return (
    <div>
      {todos.length}
    </div>
  );
}

export default connect(
  // state mapper
  function mapStateToProps(state) {
    return state.todos;
  },

  // dispatchable actions
  {
    addTodos,
    removeTodo,
  }
)(MyComponent);

Implementation can be something like this:

import { getState$ } from 'frint-redux';
import { observe, streamProps } from 'frint-react';

export default function connect(mapStateToProps, actions) {
  return function (Component) {
    return observe(function (app) {
      const store = app.get('store');

      return streamProps()
        .set(
          getState$(store),
          mapStateToProps
        )
        .setDispatch(actions, store)
        .get$();
    })(Component);
  }
}
fahad19 commented 6 years ago

Doesn't make sense to create a package for this. Read this blog post instead: https://medium.com/frintjs/using-frintjs-with-react-js-and-redux-823ad7cdbc02