-
Notifications
You must be signed in to change notification settings - Fork 18
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
Fix <With /> bug where children are not unmounted when given data is …
…null | undefined. (#131)
- Loading branch information
1 parent
8174bc4
commit cc8de36
Showing
2 changed files
with
43 additions
and
8 deletions.
There are no files selected for viewing
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
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
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -1,19 +1,23 @@ | ||
import { ReactElement } from 'react' | ||
import { useFacetMemo } from '../hooks/useFacetMemo' | ||
import { useFacetUnwrap } from '../hooks/useFacetUnwrap' | ||
import { useFacetMap } from '../hooks/useFacetMap' | ||
import { Facet, NoValue } from '../types' | ||
import { Facet, NO_VALUE } from '../types' | ||
|
||
type WithProps<T> = { | ||
data: Facet<T | null | undefined> | ||
children: (data: Facet<T>) => ReactElement | null | ||
} | ||
|
||
const hasData = <T,>(_: Facet<T | null | undefined>, shouldRender: boolean | NoValue): _ is Facet<T> => { | ||
return shouldRender === true | ||
} | ||
|
||
/** | ||
* Conditionally renders a child if a given facet value is not null or undefined | ||
* | ||
* @param data facet value which can be null or undefined | ||
* @param children render prop which receives the transformed facet | ||
*/ | ||
export const With = <T,>({ data, children }: WithProps<T>) => { | ||
const shouldRenderFacet = useFacetMap((data) => data !== null && data !== undefined, [], [data]) | ||
const shouldRender = useFacetUnwrap(shouldRenderFacet) | ||
return hasData(data, shouldRender) ? children(data) : null | ||
const nonNullData = useFacetMemo((data) => (data !== null && data !== undefined ? data : NO_VALUE), [], [data]) | ||
return shouldRender === true ? children(nonNullData) : null | ||
} |