Skip to content

Commit

Permalink
0.0.1
Browse files Browse the repository at this point in the history
  • Loading branch information
charkour committed Dec 16, 2022
0 parents commit 472f2fb
Show file tree
Hide file tree
Showing 4 changed files with 87 additions and 0 deletions.
3 changes: 3 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
node_modules
package-lock.json
dist
22 changes: 22 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
{
"name": "spritz",
"version": "0.0.1",
"description": "initalize zustand stores with react context",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [
"zustand",
"react",
"context",
"dependency-injection"
],
"author": "",
"license": "MIT",
"devDependencies": {
"@types/react": "^18.0.26",
"react": "^18.2.0",
"zustand": "^4.1.5"
}
}
28 changes: 28 additions & 0 deletions src/index.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,28 @@
import React, { createContext as createReactContext, useContext, useRef } from 'react';
import { StoreApi, useStore as useZustandStore } from 'zustand';

export const createContext = <State, Store extends StoreApi<State> = StoreApi<State>>() => {
const StoreContext = createReactContext<Store | null>(null);
const useStore = <T,>(
selector: (state: State) => T = (state) => state as unknown as T,
equalityFn: (left: T, right: T) => boolean = Object.is
) => {
const store = useContext(StoreContext);
if (!store) {
throw new Error('useProductListStore must be used within a ProductListProvider');
}
return useZustandStore(store, selector, equalityFn);
};

const Provider: React.FC<{ createStore: () => Store; children?: React.ReactNode }> = ({
createStore,
children,
}) => {
const store = useRef(createStore()).current;
return <StoreContext.Provider value={store}>{children}</StoreContext.Provider>;
};
return {
Provider,
useStore,
};
};
34 changes: 34 additions & 0 deletions tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,34 @@
{
"compilerOptions": {
"experimentalDecorators": true,
"baseUrl": ".",
"outDir": "build/dist",
"module": "ESNext",
"target": "ESNext",
"lib": ["es6", "dom", "esnext.asynciterable", "es2017"],
"sourceMap": true,
"allowJs": true,
"jsx": "react",
"moduleResolution": "node",
"rootDir": "src",
"forceConsistentCasingInFileNames": true,
"noImplicitReturns": true,
"noImplicitThis": true,
"noImplicitAny": true,
"strictNullChecks": true,
"suppressImplicitAnyIndexErrors": true,
"noUnusedLocals": true,
"skipLibCheck": true,
"allowSyntheticDefaultImports": true,
"removeComments": true
},
"exclude": [
"node_modules",
"build",
"scripts",
"acceptance-tests",
"webpack",
"jest",
"src/setupTests.ts"
]
}

0 comments on commit 472f2fb

Please sign in to comment.