---
sidebar_position: 4
---

<div class="api-link">
  <div class="api-link-title">Cache</div>
  <div class="api-link-sub-title">

[Read the API Reference »](/api/Hyper-Fetch/Class/Cache.md)

  </div>
</div>

---

---

## Introduction

**`Cache`** stores response data from requests. It uses an event system that successively transmits data and takes care
of validation in the system. Data is stored under `cacheKey` in the storage (which by default is a Map object, but can
be replaced by any other compatible interface).

---

## Purpose

- Stores request results
- Manages stored data
- Emits storage events

---

## CacheKey

The cache stores data on a `key-value` basis. The key is always specified inside the command as `cacheKey`; it
determines where the data is stored and is used in propagation of data handling events.

By default, the cacheKey value is auto-determined based on the **method**, **endpoint**, and **query params** of the
given command. However, there is nothing to prevent you manually adding the key when setting the command or using one of
its methods.

Thanks to the automatic way of indexing data in the cache, we do not have to worry about paginated keys in the data –
everything will happen automatically.

---

## Events

Available cache events.

{@import Hyper-Fetch getCacheEvents returns}

---

## Storage

By default, the cache uses Map as a data retention location. However, you can also choose where the data is stored in
the system – i.e. local storage or IndexedDB – regardless if the source works synchronously or asynchronously. This
allows you to set up persistent storage across sessions.

```tsx
export const builder = new Builder<ServerErrorType>({
  url: "localhost:3000",
  cache: (instance) =>
    new Cache(instance, {
      storage,
    }),
});
```

---

## Persistence

We can achieve the persistence of stored data by changing the cache storage to persistent. It must match the provided
interface.

#### [Read More](/guides/02-Advanced/Persistence.mdx)

:::info

Currently there is no cross-tab synchronization. It's planned for a future release.

:::

---

## Lifecycle

Cache options can be provided with some lifecycle methods. These are events such as `onInitialization`.

---

## Parameters

Configuration options

{@import Hyper-Fetch CacheOptionsType returns}
