Skip to content

#182 SSR data is shared #375

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 14 commits into from
May 5, 2021
Merged
Show file tree
Hide file tree
Changes from 7 commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
18 changes: 16 additions & 2 deletions .size-snapshot.json
Original file line number Diff line number Diff line change
Expand Up @@ -39,9 +39,9 @@
"gzipped": 354
},
"index.js": {
"bundled": 3856,
"bundled": 3857,
"minified": 1546,
"gzipped": 748,
"gzipped": 746,
"treeshaked": {
"rollup": {
"code": 124,
Expand Down Expand Up @@ -159,5 +159,19 @@
"code": 1147
}
}
},
"context.js": {
"bundled": 4680,
"minified": 2042,
"gzipped": 939,
"treeshaked": {
"rollup": {
"code": 158,
"import_statements": 38
},
"webpack": {
"code": 1176
}
}
}
}
13 changes: 13 additions & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,11 @@
"types": "./shallow.d.ts",
"module": "./esm/shallow.js",
"default": "./shallow.js"
},
"./context": {
"types": "./context.d.ts",
"module": "./esm/context.js",
"default": "./context.js"
}
},
"sideEffects": false,
Expand All @@ -40,6 +45,7 @@
"build:vanilla": "rollup -c --config-vanilla",
"build:middleware": "rollup -c --config-middleware",
"build:shallow": "rollup -c --config-shallow",
"build:context": "rollup -c --config-context",
"postbuild": "yarn copy",
"eslint": "eslint --fix 'src/**/*.{js,ts,jsx,tsx}'",
"eslint-examples": "eslint --fix 'examples/src/**/*.{js,ts,jsx,tsx}'",
Expand Down Expand Up @@ -92,6 +98,13 @@
},
"homepage": "https://github.com/react-spring/zustand",
"jest": {
"rootDir": ".",
"moduleNameMapper": {
"^zustand$": "<rootDir>/src/index.ts"
},
"modulePathIgnorePatterns": [
"dist"
],
"testRegex": "test.(js|ts|tsx)$",
"coverageDirectory": "./coverage/",
"collectCoverage": true,
Expand Down
59 changes: 59 additions & 0 deletions src/context.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,59 @@
import React, {
createContext as reactCreateContext,
useContext,
useRef,
} from 'react'
import create, { UseStore } from 'zustand'
import { EqualityChecker, State, StateCreator, StateSelector } from './vanilla'

function createContext<TState extends State>(initialState?: TState) {
const ZustandContext = reactCreateContext<UseStore<TState> | undefined>(
undefined
)

const Provider = ({
createState,
children,
}: {
createState: StateCreator<TState>
children: React.ReactNode
}) => {
const storeRef = useRef<UseStore<TState>>()

if (!storeRef.current) {
storeRef.current = create(createState)
}

return React.createElement(
ZustandContext.Provider,
{ value: storeRef.current },
children
)
}

const useStore = <StateSlice>(
selector?: StateSelector<TState, StateSlice>,
equalityFn: EqualityChecker<StateSlice> = Object.is
) => {
// ZustandContext value is guaranteed to be stable.
const useProviderStore = useContext(ZustandContext)
if (!useProviderStore) {
throw new Error(
'Seems like you have not used zustand provider as an ancestor.'
)
}
return useProviderStore(
// FIXME: this type assertion seems unnecessary, as useStore does accept undefined.
// Need to fix useStore()'s types
selector as StateSelector<TState, StateSlice>,
equalityFn
)
}

return {
Provider,
useStore,
}
}

export default createContext
68 changes: 68 additions & 0 deletions tests/context.test.tsx
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
import React from 'react'
import { cleanup, render } from '@testing-library/react'
import { StateCreator } from '../src/index'
import createContext from '../src/context'

const consoleError = console.error
afterEach(() => {
cleanup()
console.error = consoleError
})

type CounterState = {
count: number
inc: () => void
}

it('creates and uses context store', async () => {
const { Provider, useStore } = createContext<CounterState>()

const createParam: StateCreator<CounterState> = (set) => ({
count: 0,
inc: () => set((state) => ({ count: state.count + 1 })),
})

function Counter() {
const { count, inc } = useStore()
React.useEffect(inc, [inc])
return <div>count: {count}</div>
}

const { findByText } = render(
<Provider createState={createParam}>
<Counter />
</Provider>
)

await findByText('count: 1')
})

it('throws error when not using provider', async () => {
console.error = jest.fn()

class ErrorBoundary extends React.Component<{}, { hasError: boolean }> {
constructor(props: {}) {
super(props)
this.state = { hasError: false }
}
static getDerivedStateFromError() {
return { hasError: true }
}
render() {
return this.state.hasError ? <div>errored</div> : this.props.children
}
}

const { useStore } = createContext<CounterState>()
function Component() {
useStore()
return <div>no error</div>
}

const { findByText } = render(
<ErrorBoundary>
<Component />
</ErrorBoundary>
)
await findByText('errored')
})
8 changes: 7 additions & 1 deletion tsconfig.json
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,13 @@
"jsx": "preserve",
"allowSyntheticDefaultImports": true,
"esModuleInterop": true,
"moduleResolution": "node"
"moduleResolution": "node",
"baseUrl": ".",
"paths": {
"zustand": [
"./src/index.ts"
]
}
},
"include": [
"src/**/*",
Expand Down