developit / developit/unistore

[feature] Сonnect effect to store

Open
#155 2 comments 0 reactions 0 assignees View on GitHub
Dominant language
JavaScript
Stars
2.8k
Forks
134
PR merge metrics
No merged PRs in 30d

Description

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:
```js
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

```js
// in store.js
export function dispatch(action) {
const boundedAction = store.action(action);
return (...args) => boundedAction(...args);
}
```
Now we can do next
```js
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!
```js
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?

Contributor guide

No contributing guide indexed for this repository

Assessment

This issue has not been assessed yet.

Get new issues in your inbox

A short digest of beginner-friendly GitHub issues.