useAuth

API for the useAuth function

useAuth is a client side Solid hook that returns both the current session & status in addition to signIn and signOut functions.

Usage

Basic

import { useAuth } from '@solid-mediakit/auth/client'

const RenderSession = () => {
  const auth = useAuth()
  return (
    <Show
      when={auth.status() === 'authenticated' && auth.session()}
      fallback={<div>{auth.status()}</div>}
    >
      {(session) => <div>Hey there {session().user.name}</div>}
    </Show>
  )
}

auth.status // ()=> authenticated | unauthenticated | loading
auth.session // ()=> Session | null | undefined
auth.signIn // signIn function
auth.signOut // signOut function

await auth.signOut({ redirect: false })

const r = await auth.signIn('credentials', {
  redirect: false,
  email: email(),
  password: password(),
})
console.log('here', r)

Actual

const AuthShowcase: VoidComponent = () => {
  const auth = useAuth()
  const [email, setEmail] = createSignal('')
  const [password, setPassword] = createSignal('')

  return (
    <div class='flex flex-col items-center justify-center gap-4'>
      <div>
        {JSON.stringify(
          {
            status: auth.status(),
            session: auth.session(),
          },
          null,
          2,
        )}
      </div>
      <Switch fallback={<div>Loading...</div>}>
        <Match when={auth.status() === 'authenticated'}>
          <button
            onClick={async () => {
              await auth.signOut({ redirect: false })
            }}
            class='font-bold text-3xl text-red-500'
          >
            Sign Out
          </button>
        </Match>
        <Match when={auth.status() === 'unauthenticated'}>
          <div class='flex flex-col gap-4 itesms-center'>
            <input
              type='text'
              value={email()}
              placeholder='Email'
              onInput={(e) => setEmail(e.currentTarget.value)}
              class='outline-none bg-zinc-700 rounded-lg p-3 text-white text-lg font-bold'
            />
            <input
              type='password'
              value={password()}
              placeholder='Password'
              onInput={(e) => setPassword(e.currentTarget.value)}
              class='outline-none bg-zinc-700 rounded-lg p-3 text-white text-lg font-bold'
            />
            <button
              onClick={async () => {
                const r = await auth.signIn('credentials', {
                  redirect: false,
                  email: email(),
                  password: password(),
                })
                console.log('here', r)
              }}
              class='font-bold text-3xl text-green-500'
            >
              Sign In
            </button>
          </div>
        </Match>
      </Switch>
    </div>
  )
}

Preloading the session

Check this doc