0.1.12 • Published 11 months ago

@based/solidjs v0.1.12

Weekly downloads
-
License
MIT
Repository
github
Last release
11 months ago

@based/solidjs

Wraps the @based/client into SolidJS hooks and signals.

import { Show } from 'solid-js'
import type { Component } from 'solid-js'
import { useBasedQuery, BasedProvider } from '@based/solidjs'
import based, { BasedClient } from '@based/client'

const client: BasedClient = based({
  env: 'myEnv',
  org: 'myOrg',
  project: 'myProject'
})

const LoadingData: Component = () => {
  return (
    <div>Loading data...</div>
  )
}

const UsersList: Component = () => {
  const { data, error, loading } = useBasedQuery(
    'counter',
    {
      count: true,
      speed: 3000
    }
  )

  return (
    <Show when={data().children.length && !loading()} fallback={LoadingData}>
      <div>
        {
          data().children.map(({ id, name }) =>
            <p onClick={() => {
              client.call('db:delete', { id })
            }}>{name}</p>
          )
        }
      </div>
    </Show>
  )
}

const App: Component = () => {
  return (
    <BasedProvider client={client}>
      <UsersList />
    </BasedProvider>
  )
}

BasedProvider

Solid Component that inject the BasedClient context thought the application.

Aliasing

<BasedProvider client={client} liveStatus={true}>
  {/*slot*/}
</BasedProvider>

or (in deprecation process)

<Provider client={client} liveStatus={true}>
  {/*slot*/}
</Provider>

Props

ParameterTypeDefaultDescriptionRequired
clientBasedClientN/AAll the connection information that identifies you in the Based cloud.true
liveStatusbooleanfalseOption to display the BasedLiveStatus component either as an overlay or hide it.false

Slots

NameContentRequired
N/AAny component that you want to inject the BasedClient context.true

Emits

None

Basic example:

const App: Component = () => {
  return (
    <BasedProvider client={client}>
      <UsersList /> // Will receive the BasedClient context injected by the BasedProvider.
    </BasedProvider>
  )
}

useBasedContext

The BasedClient object with the information about the connection with the Based server. You cal also call functions using the client object.

Aliasing

const client = useBasedContext()

or (in deprecation process)

const client = useClient()

Params

None

Response

The BasedClient object.

import type { Component } from 'solid-js'
import { useBasedContext, BasedProvider } from '@based/solidjs'
import based, { BasedClient } from '@based/client'

const client: BasedClient = based({
  env: 'myEnv',
  org: 'myOrg',
  project: 'myProject'
})

const doSomething = (): void => {
  client.call('doSomething')
}

const context: BasedClient = useBasedContext()

const App: Component = () => {
  return (
    <BasedProvider client={client}>
      <button onClick={() => doSomething()} />
      <p>WebSockets URL: {context.opts.url.toString()}</p>
    </BasedProvider>
  )
}

useBasedQuery

Subscribe when a component gets mounted / unsubscribes when a comment gets unmounted

const useBasedQuery = <N extends keyof BasedQueryMap>(
  db: N,
  payload?: BasedQueryMap[N]['payload'],
  opts?: BasedQueryOptions,
): BasedQueryResult<BasedQueryMap[N]['result']> => {
}

Aliasing

const { data, error, loading } = useBasedQuery('myQueryFunction')

or (in deprecation process)

const { data, error, loading } = useQuery('myQueryFunction')

Types

type BasedQueryMap = {
  db: { payload: any; result: any }
  [key: string]: { payload: any; result: any }
}
type BasedQueryOptions = {
  persistent: boolean
}
type BasedQueryResult<T> = {
  loading: boolean
  data?: T
  error?: BasedError
  checksum?: number
}
class BasedError extends Error {
  public statusMessage?: string
  public code?: BasedErrorCode
}

Params

ParameterTypeDefaultDescriptionRequired
dbstring/nullN/AThe query function nametrue
payloadobjectN/AFilters and other possible mutations that you want from the queryfalse
optsobject{ persistent: false }When is true will store the cached result of a query in localStorage on the client-side. Otherwise, the cache is only in volatile memory.false

Response

KeyTypeAlways presentDescription
loadingbooleantrueIf the query is still loading.
dataanyfalseThe data coming from your filters.
errorBasedErrorfalseThe BasedError object containing the statusMessage and code from your error.
checksumnumberfalseA calculated value used to verify data integrity and detect errors. Each response has a unique checksum.

Basic example with static parameters:

import type { Component } from 'solid-js'
import { useBasedQuery } from '@based/solidjs'

const ProcessData: Component = () => {
  // With static parameters you may destruct the returned object.
  // The returned object will contain { data, loading, error, checksum } as reactive signals.
  const { data, error, loading } = useBasedQuery('myQueryFunction')

  if (error()) {
    return error.message
  }

  return (
    <Show when={data().text && !loading()} fallback={<div>Loading data...</div>}>
      <div>data().text</div>
    </Show>
  )
}

Basic example with dynamic parameters:

import { createMemo } from 'solid-js'
import type { Component } from 'solid-js'
import { useBasedQuery } from '@based/solidjs'

const ProcessData: Component = () => {
  // Update these values anywhere in your component.
  const [name, setName] = createSignal<string>()
  const [payload, setPayload] = createSignal<any>()

  // Don't destruct the returned object, will break the reactivity.
  // The returned object will contain { data, loading, error, checksum } as reactive signals.
  // Use as 'query().data()', 'query().loading()', 'query().error()', 'query().checksum()'.
  const query = createMemo(() => useBasedQuery(name(), payload()))

  if (error()) {
    return error.message
  }

  return (
    <Show when={query().data().text && !query().loading()} fallback={<div>Loading data...</div>}>
      <div>data().text</div>
    </Show>
  )
}

To persist the result of the query on localStorage on the client-side, pass persistent as true.

const { data: userInfo } = useBasedQuery(
  'someUserInfo',
  {
    id: client.authState.userId
  },
  {
    persistent: true
  }
)

Is also possible to pass a null value to the function name. This is useful when you have a query depending on other data, like Auth.

const { data: userInfo } = useBasedQuery('someUserInfo', { id: client.authState.userId })

const { data } = useBasedQuery(
  userInfo.preferedLanguage ? 'someQueryFunction' : null,
  {
    preferedLanguage: userInfo.preferedLanguage
  }
)

useBasedAuth

Check the authorization state from the Based client.

Aliasing

const auth = useBasedAuth()

or (in deprecation process)

const auth = useAuthState()

Params

None

Response

KeyTypeAlways presentDescription
tokenstringfalseThe connection token
userIdstringfalseThe connected userID.
refreshTokenstringfalseIf there is a new token provided.
errorstringfalseIf the auth fails, an error message will be provided.
persistentstringfalseIf the auth values are being stored locally on localStorage.
typestringfalseN/A.
import { useBasedAuth } from '@based/solidjs'

const IsUserAuthorized = () => {
  // The returned object is a signal.
  // Don't destruct the returned object, will break the reactivity.
  // Use as 'auth().token', 'auth().userId', 'auth().error'...
  const auth = useBasedAuth()

  if (!auth().error || !auth().token || !auth().userId) {
    return 'Not authorized 😭'
  }

  return 'Authorized! 🎉'
}

useBasedStatus

Get the connection status from the Based client.

Aliasing

const client = useBasedStatus()

or (in deprecation process)

const client = useStatus()

Enums

enum BasedStatus {
  DISCONNECT = 'disconnect',
  RECONNECT = 'reconnect',
  CONNECT = 'connect'
}

Params

None

Response

KeyTypeAlways presentDescription
connectedbooleantrueIf the connection is established or not.
statusBasedStatustrueOne of the three possible status.
import { useBasedStatus } from '@based/solidjs'

const IsBasedConnected = () => {
  // The returned object will contain { connected, status } as reactive signals.
  const { connected } = useBasedStatus()

  if (!connected()) {
    return 'Not connected 😭'
  }

  return 'Connected! 🎉'
}
0.1.12

11 months ago

0.1.11

11 months ago

0.1.10

11 months ago

0.1.9

11 months ago

0.1.8

11 months ago

0.1.7

11 months ago

0.1.6

12 months ago

0.1.5

12 months ago

0.1.4

12 months ago

0.1.3

12 months ago

0.1.2

12 months ago

0.1.1

12 months ago

0.1.0

12 months ago