developit / unistore

🌶 350b / 650b state container with component actions for Preact & React
https://npm.im/unistore
2.86k stars 139 forks source link

[feature] Сonnect effect to store #155

Open Akiyamka opened 5 years ago

Akiyamka commented 5 years ago

Hello. I want to offer an interesting feature. How about making connect able to take not only a component but also an effect? At first glance it sounds strange, but let's look at the use-cases.

For example, I want to get some data from the API before the application renders some part of the application. There are many ways to do this. HOC with RenderProps where we use componentDidMount, or just useEffect. If we use useEffect we need to import some methods to initialize the query into API, data conversion ect. It is best to make it a separate effect useSomething(id). Result of useSomething we wont push to store. So what we have:

import { useEffect, useRef } from 'react';
import store from 'Services/store';
import { callSomeApi } from 'Api/something';

export default function useSomething() {
  const lastId = useRef()

  useEffect(async () => {
    return store.subscribe(({ id }) => {
     if (lastId.current !== id) {
        lastId.current = id;
        const result await = callSomeApi();
        store.setState({ something: result });
     }
    });

  }, []);

}

Of course better if we use action instead store.setState so i add my custom dispatch

// in store.js
export function dispatch(action) {
  const boundedAction = store.action(action);
  return (...args) => boundedAction(...args);
}

Now we can do next

import { useEffect, useRef } from 'react';
import store, { actions } from 'Services/store';

export default function useSomething() {
  const lastId = useRef()

  useEffect(async () => {
    return store.subscribe(({ id }) => {
     if (lastId.current !== id) {
        lastId.current = id;
        dispatch(actions.setSomething)(id);
     }
    });

  }, []);

}

Still pretty much code.

But let's imagine that connect takes effect. It would be cool if we could do this!

import { useEffect, useRef } from 'react';
import store, { actions } from 'Services/store';

function useSomething({ id, setSomething }) {
  useEffect(() => {
     dispatch(setSomething)(id);
  }, [id]);
}
export default connect('foo,bar', actions)(useSomething)

What do you think about it?

Akiyamka commented 5 years ago

I try to do it myself, but I do not have enough experience to understand how to run a hook in the context of the component. As a result, I get an error:

Invalid hook call. Hooks can only be called inside of the body of a function component.

My attempt:

export function connectEffect(mapStateToProps, actions) {
  if (typeof mapStateToProps !== 'function') {
    mapStateToProps = select(mapStateToProps || []);
  }
  const boundActions = actions ? mapActions(actions, store) : { store };

  return Effect => {
    return ownProps => {
      const update = state => {
        const mapped = mapStateToProps(state, ownProps = {});
        for (let i in mapped) if (mapped[i] !== state[i]) {
          state = mapped;
          return triggerEffect(state);
        }

        for (let i in state) if (!(i in mapped)) {
          state = mapped;
          return triggerEffect(state);
        }
      };
      const unsubscribe = store.subscribe(update);
      let clearEffect = () => { };
      const triggerEffect = state => {
        clearEffect = Effect({ ...ownProps, ...boundActions, ...state });
      };

      return () => {
        unsubscribe();
        clearEffect();
      };
    };
  };
}
developit commented 4 years ago

I think we're going to look into adding a dedicated hooks API for the React and Preact unistore integrations.