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.

Note that isReady() and isReadyAsync() will always return false on server-side. It only becomes true after the first successful call to setup() on the client.

Usage

Basic

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

import {  } from '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 '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 false until they are properly rehydrated on the client.

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

import { dehydrate, hydrate, createPermix } from '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: false } }
 
// Rehydrate permissions on the client
hydrate(permix, state)
 
const canRead = permix.check('post', 'read', { isPublic: true }) // false
 
permix.hook('ready', (state) => {
  const canRead = permix.check('post', 'read', { isPublic: true })
  console.log(canRead) // true
})

On this page