Skip to content

Instantly share code, notes, and snippets.

@meshaabi
Created July 25, 2023 15:16
Show Gist options
  • Save meshaabi/233e0f65d3926a2a77147e2a316d531b to your computer and use it in GitHub Desktop.
Save meshaabi/233e0f65d3926a2a77147e2a316d531b to your computer and use it in GitHub Desktop.
import create, { GetState, Mutate, SetState, StateCreator, StoreApi } from 'zustand';
import { persist, subscribeWithSelector } from 'zustand/middleware';
import AsyncStorage from '@react-native-async-storage/async-storage';
import zustandFlipper from 'react-native-flipper-zustand';
import { areWeTestingWithJest } from 'utils/jest';
import { createStoresSlice } from './stores/store';
import { AllStoreSlices } from './useStoreTypes';
import { createAppSlice } from './app/store';
import { createCustomerSlice } from './customer/store';
import { createRemoteConfigSlice } from './remoteConfig/store';
import { createBasketSlice } from './basket/store';
type ZustandFlipper = (config: StateCreator<AllStoreSlices>) => StateCreator<AllStoreSlices>;
const combineStateSlices = (set: SetState<AllStoreSlices>): AllStoreSlices => ({
...createAppSlice(set),
...createRemoteConfigSlice(set),
...createStoresSlice(set),
...createCustomerSlice(set),
...createBasketSlice(set),
});
export const useStore = create<
AllStoreSlices,
SetState<AllStoreSlices>,
GetState<AllStoreSlices>,
Mutate<
StoreApi<AllStoreSlices>,
[['zustand/subscribeWithSelector', never], ['zustand/persist', Partial<AllStoreSlices>]]
>
>(
subscribeWithSelector(
persist(
__DEV__ && !areWeTestingWithJest()
? (zustandFlipper as ZustandFlipper)(set => combineStateSlices(set))
: set => combineStateSlices(set),
// Persist config
{
name: 'made-app-storage',
getStorage: () => AsyncStorage,
// Returning a function to be called after rehydration
onRehydrateStorage: () => state => {
state?.setStorageHydrated(true);
},
// This is where we specify which bits of state we want to persist:
partialize: state => ({
currentStore: state.currentStore,
isRemoteConfigReady: state.isRemoteConfigReady,
remoteConfig: state.remoteConfig,
}),
},
),
),
);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment