Customizing Cell behavior
I have a Cell that displays items in a shopping cart.
I ran in to two problems while doing this
First problem
To grab all the items a gql query is made, with a unique shopping cart ID passed as a parameter. This ID is stored in global state, and might not always be available when this Cell is being displayed. But most likely it will be available very shortly after.
So I display my cell like this
<CartCell checkoutId={checkoutId} />
I could do this instead
{checkoutId && <CartCell checkoutId={checkoutId} />}
But I wanted the Cell’s “loading” state to be shown while waiting for the checkout ID to be populated in my global state
So what I did in my Cell was this
export const Failure = ({ error, variables }) => {
if (!variables.checkoutId) {
return <Loading />
}
return <div>Error: {error.message}</div>
}
And this works, but I’m getting error logs in my console: Error: Variable "$checkoutId" of required type "String!" was not provided.
My second try at handling this what like so (notice the skip
):
export const beforeQuery = (props) => {
return {
variables: props,
fetchPolicy: 'network-only',
skip: !props.checkoutId,
}
}
But doing that, I get this error: Uncaught Cannot render cell: graphQL success but
data is null
So what I’m doing now is importing both the entire Cell plus the Loading state component and displaying them like this
{checkoutId && <CartCell checkoutId={checkoutId} />}
{!checkoutId && <Loading />}
Is this the best way to do it?
Second problem
When getting the cart, and it’s empty, I’d like to show the “empty” state, i.e. render <Empty />
. But to do that I have to do this
export const Success = ({ cart }) => {
if (cart.items.length === 0) {
return <Empty />
}
return <CartTable cart={cart} />
}
Solution/Discussion points/Ideas
If it was possible to customize the “loading” state condition I could include checkoutId === undefined
there and not need the if (!variables.checkoutId) return <Loading />
check in the “failure” state.
If it was possible to customize the “empty” state condition I could include cart.items.length === 0
there, and not need the special handling in the “success” state.
If Cells added a “skipped” state, with a corresponding <Skipped />
component, Cells would be able to handle setting skipped: true
in beforeQuery
. Users would be free to export const Skipped = Failure
or export const Skipped = Empty
, depending on what behavior is wanted.
What do you all think of the problem, and my ideas to solve it?