Open Akiyamka opened 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();
};
};
};
}
I think we're going to look into adding a dedicated hooks API for the React and Preact unistore integrations.
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 justuseEffect
. 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 effectuseSomething(id)
. Result of useSomething we wont push to store. So what we have:Of course better if we use action instead
store.setState
so i add my custom dispatchNow we can do next
Still pretty much code.
But let's imagine that connect takes effect. It would be cool if we could do this!
What do you think about it?