Permix

Ready State

Learn how to use the `isReady()` method to check if permissions are ready to use.

Overview

Sometimes you need to know when permissions are ready to use. For example, you might want to wait for permissions to be ready before rendering a component. That's where the isReady() and isReadyAsync() methods come in.

isReady() and isReadyAsync() always return false on the server. On the client they become true after the first successful setup() call or after hydrating a complete boolean-only snapshot.

Usage

Basic

Permix provides an isReady() method to check if permissions have been properly initialized on the client side:

import {  } from '@aminzoubaa/permix'

const  = ()

.(.()) // false

// After setup completes
.({
  : {
    : true,
    : true
  }
})

.(.()) // true

Async

If you need to wait for permissions to be ready in an async context, you can use the isReadyAsync() method. This returns a promise that resolves when permissions are ready:

import { createPermix } from '@aminzoubaa/permix'

const permix = createPermix()

async function init() {
  await permix.isReadyAsync()
  // Permissions are now ready to use
  const canCreate = permix.check('post', 'create')
}

SSR

This is particularly useful in SSR applications when using function-based permissions, since the dehydration process converts all function permissions to null until they are properly restored on the client.

Read more about hydration to learn how to transfer permissions from the server to the client.

import { dehydrate, hydrate, createPermix } from '@aminzoubaa/permix'
import { permix } from './permix'

permix.setup({
  post: {
    create: true,
    read: post => post.isPublic
  }
})

// Dehydrate permissions on the server
const state = dehydrate(permix)
// { post: { create: true, read: null } }

// Rehydrate permissions on the client
hydrate(permix, state)

const canRead = permix.check('post', 'read', { isPublic: true }) // false

permix.setup({
  post: {
    create: true,
    read: post => post.isPublic
  }
})

permix.hook('ready', () => {
  const canRead = permix.check('post', 'read', { isPublic: true })
  console.log(canRead) // true
})