You may use React Native MMKV for PocketBase CustomAuthStore and the integration is very straightforward.
Install Dependencies
npx expo install react-native-mmkv pocketbase
Define MMKV Store
// @/store/MMKV.ts
import {MMKV} from "react-native-mmkv";
export const storage = new MMKV();
Once you have defined the above store, the next part is to define the "CustomAuthStore" and export it.
Define CustomAuthStore
You can define the following CustomAuthStore and provide the implementation to CRUD to MMKV.
// @/store/CustomAuthStore.ts
import {Admin, BaseAuthStore, Record} from "pocketbase";
import {storage} from "./MMKV";
import {MMKV} from "react-native-mmkv";
export default class CustomAuthStore extends BaseAuthStore {
private storageFallback: { [key: string]: any } = {};
private storageKey: string;
private mmkv: MMKV;
constructor(storageKey = "pocketbase_auth") {
super();
this.storageKey = storageKey;
this.mmkv = storage;
}
get token(): string {
const data = this._storageGet(this.storageKey) || {};
return data.token || '';
}
get model(): Record | Admin | null {
const data = this._storageGet(this.storageKey) || {};
if (
data === null ||
typeof data !== 'object' ||
data.model === null ||
typeof data.model !== 'object'
) {
return null;
}
if (typeof data.model?.collectionId === 'undefined') {
return new Admin(data.model);
}
return new Record(data.model);
}
save(token: string, model: Record | Admin | null) {
this._storageSet(this.storageKey, {
'token': token,
'model': model,
});
super.save(token, model);
}
clear() {
this._storageRemove(this.storageKey);
super.clear();
}
private _storageGet(key: string): any {
if (typeof MMKV !== 'undefined') {
const rawValue = this.mmkv.getString(key) || '';
try {
return JSON.parse(rawValue);
} catch (e) { // not a json
return rawValue;
}
}
return this.storageFallback[key];
}
private _storageSet(key: string, value: any) {
if (typeof MMKV !== 'undefined') {
let normalizedVal = value;
if (typeof value !== 'string') {
normalizedVal = JSON.stringify(value);
}
this.mmkv.set(key, normalizedVal);
} else {
this.storageFallback[key] = value;
}
}
private _storageRemove(key: string) {
if (typeof MMKV !== 'undefined') {
this.mmkv.delete(key);
}
delete this.storageFallback[key];
}
}
Instantiate PocketBase with CustomAuthStore
The next step is to instantiate `PocketBase` with the `CustomAuthStore` and export it.
// @/store/Pocketbase.ts
import PocketBase from "pocketbase";
import CustomAuthStore from "./CustomAuthStore";
const URL = 'https://your-url-here.test/';
export default new PocketBase(URL, new CustomAuthStore());
Explore all our HestiaKit Components and easily transform your idea into working apps in hours.