-
-
Save SaiEashwarKS/90226c7216ca1a8c88acd7a067358348 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import React, { useEffect, useState } from 'react'; | |
import { SingleItemContainer } from './SingleItemContainer'; | |
import { Hook } from './singletonHookTypes'; | |
let SingletonHooksContainerMounted = false; | |
export let mountIntoContainer: <HookReturn = any, HookArgs extends any[] = any[]>( | |
hook: Hook<HookReturn, HookArgs> | |
) => void; | |
export let unmountFromContainer: <HookReturn = any, HookArgs extends any[] = any[]>( | |
hook: Hook<HookReturn, HookArgs> | |
) => void; | |
export const SingletonHooksContainer = () => { | |
useEffect(() => { | |
if (SingletonHooksContainerMounted) { | |
console?.log?.( | |
'SingletonHooksContainer is mounted second time. ' + | |
'You should mount SingletonHooksContainer before any other component and never unmount it.' | |
); | |
} | |
SingletonHooksContainerMounted = true; | |
return () => { | |
SingletonHooksContainerMounted = false; | |
}; | |
}, []); | |
const [hooks, setHooks] = useState<Hook[]>([]); | |
useEffect(() => { | |
mountIntoContainer = (newHook: Hook) => setHooks((hooks) => [...hooks, newHook]); | |
unmountFromContainer = (hookToUnmount: Hook) => | |
setHooks((hooks) => hooks.filter((hook) => hook.useHookBody !== hookToUnmount.useHookBody)); | |
setHooks([]); | |
}, []); | |
return ( | |
<> | |
{hooks.map((hook, index) => ( | |
<SingleItemContainer {...hook} key={index} /> | |
))} | |
</> | |
); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment