Files
landscape-template/src/utils/hooks/useReduxEffect.ts
MTG2000 9a8dc9431b fix: fixing pre-launch issues
- refactor the tags topics stuff (apis/mocks/components)
- update TagsInput
- Change how feed page looks on tags filtering
2022-06-14 17:40:47 +03:00

43 lines
1.1 KiB
TypeScript

import { useRef, useEffect, useCallback } from 'react'
import { Action } from '@reduxjs/toolkit'
import { useStore } from 'react-redux'
/**
* Subscribes to redux store events
*
* @param effect
* @param type
*/
export function useReduxEffect<TAction extends Action>(
effect: (action: TAction) => void,
type: string | string[],
): void {
const currentValue = useRef(null)
const store = useStore()
const handleChange = useCallback(() => {
const state = store.getState() as any;
const action = state.action
const previousValue = currentValue.current
currentValue.current = action.count
if (
previousValue !== action.count &&
castArray(type).includes(action.type)
) {
effect(action)
}
}, [effect, store, type])
useEffect(() => {
const unsubscribe = store.subscribe(handleChange)
return (): void => unsubscribe()
}, [handleChange, store])
}
// Native
function castArray<T>(arr: T | Array<T>) {
return Array.isArray(arr) ? arr : [arr]
}