Skip to content

Commit

Permalink
fix(mutation): create a new state instead of mutating initialValues t…
Browse files Browse the repository at this point in the history
…o prevent readonly errors
  • Loading branch information
BowlingX committed Dec 13, 2019
1 parent a754524 commit 4c4c543
Show file tree
Hide file tree
Showing 3 changed files with 28 additions and 12 deletions.
11 changes: 10 additions & 1 deletion src/examples/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,18 +6,27 @@ import Geschichte, { factoryParameters, pm, serializers } from '../index'
const history = createBrowserHistory()

const config = {
abc: {
test: pm('z', serializers.string)
},
arg: pm('arg', serializers.string),
test: pm('foo', serializers.string)
}

const { useQuery } = factoryParameters(config, {
abc: {
test: 'arg'
},
arg: 'blub',
test: 'haha'
})

const { useQuery: useAnotherQuery } = factoryParameters(
config,
{
abc: {
test: 'arg'
},
arg: 'xyz',
test: 'another'
},
Expand Down Expand Up @@ -59,7 +68,7 @@ const DifferentApp = () => {
export const App = () => (
<>
<Geschichte history={history}>
<h3>A sample Applications</h3>
<h3>A sample Appliations</h3>
<InnerApp />
<DifferentApp />
</Geschichte>
Expand Down
4 changes: 3 additions & 1 deletion src/geschichte.stories.mdx
Original file line number Diff line number Diff line change
Expand Up @@ -34,4 +34,6 @@ export const App = () => (

## Test

<App />
<Preview>
<App />
</Preview>
25 changes: 15 additions & 10 deletions src/lib/store.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
/* tslint:disable:no-expression-statement readonly-array no-shadowed-variable */
import { History } from 'history'
import LocationState = History.LocationState

import produce from 'immer'
import memoizeOne from 'memoize-one'
import { stringify } from 'query-string'
import {
Expand Down Expand Up @@ -79,18 +79,23 @@ export const factoryParameters = <T = object>(
const initBlank = (initialQueries: object) => {
// thisValues will be mutated by applyFlatConfigToState, that's why we init it with a copy of
// the initial state.
const thisValues = { ...defaultInitialValues }
const thisQuery = applyFlatConfigToState(
flatConfig,
initialQueries,
ns,
thisValues,
defaultInitialValues
)
// tslint:disable-next-line:no-let
let thisQuery = {}
// We produce a new state here instead of mutating defaultInitialValues.
// Otherwise it's possible that it get's reused across executions and that will yield to readonly errors.
const values = produce(defaultInitialValues, draft => {
thisQuery = applyFlatConfigToState(
flatConfig,
initialQueries,
ns,
draft as T,
defaultInitialValues as T
)
})
return {
initialValues: defaultInitialValues,
query: thisQuery,
values: thisValues
values
}
}

Expand Down

0 comments on commit 4c4c543

Please sign in to comment.