SolidJSS
SolidJSโ€ข2mo agoโ€ข
1 reply
hyperknot

Show guard inside or outside component?

I have a session() getter that throws if called before sessionID is set:

session() {
  session() {
    const { sessionID } = this.state
    if (!sessionID) throw new Error('Session ID not set')

    const session = sessionStore.sessionMap.get(sessionID)
    if (!session) throw new Error('Session not found')

    return session
  }
}


For components that depend on this, what's the recommended Solid pattern?

A) Require the parent to wrap in <Show> outside, but can be missed any time in a future refactor.

        <Show when={props.chat.state.sessionID}>
          <ToggleStarred chat={props.chat} />
        </Show>


B) Put the <Show> inside the component, making it safe to use anywhere.

export const ToggleStarred: Component<ChatProps> = (props) => {
  const session = () => (props.chat.state.sessionID ? props.chat.session() : null)
  const isStarred = () => session()?.state.starred ?? false

  return (
    <Show when={session()}>
      {(s) => (
        <button
          onClick={() => s().setStarred(!isStarred())}
          aria-pressed={isStarred()}
          aria-label={isStarred() ? 'Remove Star' : 'Add Star'}
        >
          <StarIcon
            fill={isStarred() ? 'currentColor' : 'none'}
            classList={{
              'text-amber-400': isStarred(),
              'text-neutral-400': !isStarred(),
            }}
          />
        </button>
      )}
    </Show>
  )
}


Leaning B for safety / code readability, but curious if there's a reactivity/performance reason to prefer A, or a third option I'm missing?
Was this page helpful?