# PlayerData: set() method

> The set() method of the PlayerData interface writes a key's value and resolves with its new version.

The **`set()`** method of the [`PlayerData`](/docs/room/player-data) interface writes a key's value and resolves with its new version.

## Syntax

```ts
set(key, value)
set(key, value, options)
```

### Parameters

`key`
: The key, 1 to 64 of `A-Z a-z 0-9 _ . : -`.

`value`
: JSON, or a `Uint8Array`, at most 64 KB. `undefined` is stored as `null`.

`options` Optional
: An object with any of these properties:

  `version`
  : The version the key must have, or the write fails with `E_VERSION`. `0` means the key must have none. Without it, the write is unconditional.

  `once`
  : A key, 1 to 64 of `A-Z a-z 0-9 _ . : -`, that makes the write safe to repeat: a write with a `once` key the project used in the last day doesn't run again, and resolves as the first did. The same key with different arguments fails with `E_INVALID`.

### Return value

A `Promise` that resolves with `{ version }`, the key's new version.

### Exceptions

The promise rejects with a [`DataError`](/docs/room/data-error) whose `code` is, among others:

`E_VERSION`
: The key doesn't have the `version` given.

`E_QUOTA`
: The write would take the player over 256 keys or 1 MB.

`E_INVALID`
: The key or value is malformed or over 64 KB, or `once` was used with different arguments.

`E_UNAVAILABLE`
: The data service couldn't be reached. The write may or may not have happened; repeat it with `version` or `once`.

## Examples

### Saving progress only over what was loaded

```ts
// checkpoint.ts
import { DataError, defineRoom } from "@irtio/room";

export default defineRoom({
  async onJoin(room, connection) {
    const save = await room.playerData(connection.player).get<{ checkpoint: number }>("progress");
    connection.data.checkpoint = save?.value.checkpoint ?? 0;
    connection.data.version = save?.version ?? 0;
  },
  async onMessage(room, connection, message) {
    if (message !== "checkpoint") return;
    const progress = { checkpoint: connection.data.checkpoint + 1 };
    try {
      const { version } = await room.playerData(connection.player).set("progress", progress, { version: connection.data.version });
      connection.data.checkpoint = progress.checkpoint;
      connection.data.version = version;
    } catch (e) {
      if (e instanceof DataError && e.code === "E_VERSION") room.kick(connection, "your save changed elsewhere; rejoin");
      else throw e;
    }
  },
});
```

## See also

- [`PlayerData.increment()`](/docs/room/player-data/increment), for counters
- [Writes that may or may not have happened](/docs/room/guides/player-data#writes-that-may-or-may-not-have-happened)
