Safe to throw in selectors? #1968
-
Hi! I'm working on a project and I have a situation kind of like this: type FooBarState =
| { status: 'foo', foo: string }
| { status: 'bar', bar: string };
const FooBar = () => {
const status = useSelector((state: RootState) => state.fooBar.status;
if (status === 'foo') return <Foo />;
return <Bar />;
}
const Foo = () => {
const foo = useAppSelector((state: RootState) => {
// Throwing an error here to narrow the type
// this component only ever get rendered
if (state.fooBar.status !== 'foo') throw new Error('Not foo!');
return state.fooBar.foo;
});
return <p>{foo}</p>;
}
const Bar = // Same kind of thing In this simplified example, it would be just as easy to return This situation seems similar to the zombie child problem and in my experimentation, react-redux handles this gracefully as far as I can tell. The only time the selector throws is when the state changes so that e.g. The section of the docs talking about zombie children mentions that you shouldn't depend on selectors throwing, so I wanted to ask, is this pattern safe? To clarify, I'm not throwing or catching errors in selectors as flow control or to do any side-effects or anything -- it's only in this "selector is invalid in the current state" situation. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 1 reply
-
Seems like you're aware of what happens when you throw in a component and are treating that as an intentional "this went wrong" behavior with an error boundary. So, while it's not a pattern I would normally recommend, seems like you've got your bases covered here. |
Beta Was this translation helpful? Give feedback.
Seems like you're aware of what happens when you throw in a component and are treating that as an intentional "this went wrong" behavior with an error boundary. So, while it's not a pattern I would normally recommend, seems like you've got your bases covered here.