segmentio / analytics-react-native

The hassle-free way to add analytics to your React-Native app.
https://segment.com/docs/sources/mobile/react-native/
MIT License
354 stars 181 forks source link

Example using MMKV as the storePersistor? #911

Closed thianphat closed 4 months ago

thianphat commented 5 months ago

Does anyone have a working example of utilizing MMKV storage instead of Async Storage? Getting this error when adding MMKV storage to storePersistor

persistor.get is not a function (it is undefined)

Screenshot 2024-01-11 at 1 23 22 PM

Screenshot 2024-01-11 at 1 23 55 PM

joeruello commented 5 months ago

@thianphat If you're still looking for an example:

import { createClient } from '@segment/analytics-react-native';
import { MMKV } from 'react-native-mmkv'

const storage = new MMKV({
  id: 'mycoolapp:segment',
});

const mmkvStorePersistor = {
  async get<T>(key: string) {
    try {
      const value = storage.getString(key);
      if (value !== null && value !== undefined) {
        return JSON.parse(value) as unknown as T;
      }
    } catch (e) {
      console.error(e);
    }

    return undefined;
  },
  async set<T>(key: string, value: T) {
    try {
      storage.set(key, JSON.stringify(value));
    } catch (e) {
      console.error(e);
    }
  },
};

export const segmentClient = createClient({
  writeKey: 'YOUR_WRITE_KEY',
  storePersistor: mmkvStorePersistor,
})

Based off the AysncStorage impl in this repo: https://github.com/segmentio/analytics-react-native/blob/87f34e3ae318f85666ef1b8b94b5646e138bda17/packages/sovran/src/persistor/async-storage-persistor.ts#L36-L63

oscb commented 4 months ago

@joeruello thanks for that great example!

@thianphat here's the interface of the Persistor for reference, is not a 1-to-1 match to MMKV or other storages but a simplified version of it: https://github.com/segmentio/analytics-react-native/blob/87f34e3ae318f85666ef1b8b94b5646e138bda17/packages/sovran/src/persistor/persistor.ts#L20-L31

thianphat commented 3 months ago

@oscb @joeruello very helpful. thank you so much!