How think about useSusepenseAtomValue
hook?
#3027
-
We often use React with components like What if we have a component that only signed-in users can access? const userAtom = atom<{name:string; age:number}|null>(null)
function ProfileButton(){
const user = useAtomValue(userAtom);
return (
<button>{user?.name}</button>
)
} I think the code below could be clearer: function useSuspenseAtomValue(atom:Atom<T>){
const value = useAtomValue(atom);
if(value === null || value === unedfined) throw new Error('atom is nullable') // check value is nullable. throw to ErrorBoundary
return value;
} <ErrorBoundary fallback={null}>
<ProfileButton/>
</ErrorBoundary>
// ..
function ProfileButton(){
const user = useSuspenseAtomValue(userAtom);
return (
<button>{user.name}</button>
)
} This simple code snippet realy find to me. |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 3 replies
-
Additionally, the cases below make the code a little more complex. const categoryAtom = atom<string|null>(null);
const filterByCategory(list:Item, category:string) => list.filter(item => item.category !== category);
// ...
function App(){
const category = useAtomValue(categoryAtom)
const filtered = filterByCategory([...], category) // type error string|null is not assign able to type 'string'
return ( ... )
}
|
Beta Was this translation helpful? Give feedback.
-
If it works for you, it works for you. |
Beta Was this translation helpful? Give feedback.
It seems unrelated to Suspense, so I'd call it
useNonNullableAtomValue
.