import React , { useEffect , useCallback , createContext , useContext , useRef } from 'react' ; import { useMultiContent , HookProps , Content , MultiContent } from './use_multi_content' ; const multiContentContext = createContext < MultiContent < any > > ( { } as MultiContent < any > ) ; interface Props < T extends object > extends HookProps < T > { children : JSX . Element | JSX . Element [ ] ; } export function MultiContentProvider < T extends object = { [ key ] : any ; } > ( { defaultValue , onChange , children , } ) { const multiContent = useMultiContent < T > ( { defaultValue , onChange } ) ; return ( < multiContentContext . Provider value = { multiContent } > { children } < /multiContentContext.Provider>); } export const MultiContentConsumer = multiContentContext . Consumer ; export function useMultiContentContext < T extends object = { [ key ] : any ; } > ( ) { const ctx = useContext ( multiContentContext ) ; if ( Object . keys ( ctx ) . length === 0 ) { throw new Error ( 'useMultiContentContext must be used within a <MultiContentProvider />' ) ; } return ctx as MultiContent < T > ; } param contentId export function useContent < T extends object , K extends keyof T > ( contentId ) { const isMounted = useRef ( false ) ; const defaultValue = useRef < T [ K ] | undefined > ( undefined ) ; const { updateContentAt , saveSnapshotAndRemoveContent , getData , getSingleContentData , } = useMultiContentContext < T > ( ) ; const updateContent = useCallback ( ( content ) => { updateContentAt ( contentId , content ) ; } , [ contentId , updateContentAt ] ) ; useEffect ( ( ) => { return ( ) => { saveSnapshotAndRemoveContent ( contentId ) ; } ; } , [ contentId , saveSnapshotAndRemoveContent ] ) ; useEffect ( ( ) => { if ( isMounted . current === false ) { isMounted . current = true ; } } , [ ] ) ; if ( isMounted . current === false ) { defaultValue . current = getSingleContentData ( contentId ) ; } return { defaultValue : defaultValue . current ! , updateContent , getData , getSingleContentData , } ; }