Skip to content
/ crate Public

A simple to use, scalable state container built for the roblox-ts ecosystem.

License

Notifications You must be signed in to change notification settings

Neohertz/crate

Repository files navigation

Crate

Crate

A simple to use, scalable state container built for the roblox-ts ecosystem

📛 Notice

Caution

While crate appears to be stable, v1.0.1 has not been thoroughly battle tested. Use at your own risk, as you may encounter breaking bugs.

💻 Installation

To install crate, run one of the following commands in your project's directory.

npm i @rbxts/crate
yarn add @rbxts/crate
pnpm add @rbxts/crate

💫 Usage

Below is a basic example of using crate to manage player data.

import { Crate } from "@rbxts/crate";
import { Players } from "@rbxts/services";

enum AUTH_LEVEL {
  USER,
  ADMIN,
}

interface User {
  player: Player;
  authLevel: AUTH_LEVEL;

  stats: {
    cash: 0;
  };
}

// Determine a player's auth level.
function getUserAuthLevel(player: Player) {
  return player.UserId === 1 ? AUTH_LEVEL.ADMIN : AUTH_LEVEL.USER;
}

// Create and return a crate for the provided user.
function createUserCrate(player: Player): Crate<User> {
  const user = new Crate<User>({
    player: player,
    authLevel: getUserAuthLevel(player),

    stats: {
      cash: 0,
    },
  });

  return user;
}

// Listen for player join.
Players.PlayerAdded.Connect((player) => {
  const user = createUserCrate(player);

  // Listen to updates to the player's cash.
  user.onUpdate(
    (state) => state.stats.cash,
    (cash) => print(cash),
  );

  // If the user is an admin, give them a bunch of cash.
  if (user.getState((s) => s.authLevel) === AUTH_LEVEL.ADMIN) => {
    user.update({
      stats: {
        cash: 1000000,
      },
    });
  })  
});

Note

To learn more, visit the docs.

⚛️ React

For more information on using crates with react, see @rbxts/react-crate.