marvelapp / react-ab-test

A/B testing React components and debug tools. Isomorphic with a simple, universal interface. Well documented and lightweight. Tested in popular browsers and Node.js. Includes helpers for Mixpanel and Segment.com.
MIT License
243 stars 46 forks source link

feat: replaces noop store with memory store #29

Open gabteles opened 3 years ago

gabteles commented 3 years ago

Table of Contents

Description

This implements a basic memory store instead of noop.

Motivation and Context

When server-side rendering, having a noop store causes useExperiment calls to fail even if they were made after a emitter.defineVariants call.

How Has This Been Tested?

I've added tests to store.jsx to check if it could set and get items from it. The most important part is to delete window.localStorage and keep it working properly.

Screenshots (if appropriate):

Types of changes

Checklist:

moretti commented 3 years ago

Hey Gabriel, thank you for this!

There's another PR that it's adding a cookie storage for browsers that do not support window.localstorage: https://github.com/marvelapp/react-ab-test/pull/28 Just thinking about what could be the best way to support every scenario...this could a third fallback option?

Basically when localStorage and and cookieStorage are not available, which would be the case of node.js running without JSDOM, then we could fallback to memoryStorage...what do you think?

gabteles commented 3 years ago

I think memoryStorage should be the last fallback option, indeed, since it's not persistent across navigation through pages. In order to support multiple stores, we could introduce an interface like this (using typescript just to illustrate):

interface IStorage {
  isAvailable(): boolean;
  getItem(key: string): string | null;
  setItem(key: string, value: string): void;
}

So we could select storage like this:

const localStorageWrapper = {
  isAvailable() {
    if (typeof window === 'undefined' || !'localStorage' in window) {
      return false
    }

    try {
      let key = '__pushtell_react__';
      window.localStorage.setItem(key, key);
      if (window.localStorage.getItem(key) === key) {
        window.localStorage.removeItem(key);
        return true;
      }
    } catch (e) {
      // DO NOTHING 
    }

    return false
  },
  getItem(key) { return localStorage.getItem(key) },
  setItem(key, value) { localStorage.setItem(key, value) }
}

const cookieStorageWrapper = {
  // ...
}

const memoryStorageWrapper = {
  values: {},
  isAvailable() { return true },
  getItem(key) { return this.values[key] },
  setItem(key, value) { this.values[key] = value }
}

// Ordered by preference 
const storages = [
  localStorageWrapper,
  cookieStorageWrapper,
  memoryStorageWrapper
]

const availableStorage = storages.find((storage) => storage.isAvailable())
export default availableStorage;