( defaultState: State, props?: Config, )
| 250 | 'undefined is used to skip updates. To allow undefined as a value provide explicit { skipVoid: false } option' |
| 251 | |
| 252 | export function createStore<State>( |
| 253 | defaultState: State, |
| 254 | props?: Config, |
| 255 | ): Store<State> { |
| 256 | const config = flattenConfig(props) |
| 257 | const plainState = createStateRef(defaultState) |
| 258 | const errorTitle = generateErrorTitle('store', config) |
| 259 | const updates = createEvent({named: 'updates', derived: true}) |
| 260 | applyTemplate('storeBase', plainState) |
| 261 | const plainStateId = plainState.id |
| 262 | |
| 263 | // skipVoid deprecation rules |
| 264 | const explicitSkipVoid = 'skipVoid' in config |
| 265 | const voidValueAllowed = explicitSkipVoid && !config.skipVoid |
| 266 | const skipVoidTrueSet = explicitSkipVoid && config.skipVoid |
| 267 | |
| 268 | deprecate(!skipVoidTrueSet, '{skipVoid: true}', 'updateFilter', errorTitle) |
| 269 | |
| 270 | const store = { |
| 271 | updates, |
| 272 | defaultState, |
| 273 | stateRef: plainState, |
| 274 | getState() { |
| 275 | let targetRef = plainState |
| 276 | let reachedPage |
| 277 | if (currentPage) { |
| 278 | let page = currentPage |
| 279 | while (page && !page.reg[plainStateId]) { |
| 280 | page = getParent(page) |
| 281 | } |
| 282 | if (page) reachedPage = page |
| 283 | } |
| 284 | if (!reachedPage && forkPage) { |
| 285 | initRefInScope(forkPage, plainState, true) |
| 286 | reachedPage = forkPage |
| 287 | } |
| 288 | if (reachedPage) targetRef = reachedPage.reg[plainStateId] |
| 289 | return readRef(targetRef) |
| 290 | }, |
| 291 | setState: (state: State) => |
| 292 | launch({ |
| 293 | target: store, |
| 294 | params: state, |
| 295 | defer: true, |
| 296 | scope: forkPage!, |
| 297 | }), |
| 298 | reset(...units: CommonUnit[]) { |
| 299 | assert( |
| 300 | // @ts-expect-error |
| 301 | store.targetable, |
| 302 | '.reset of derived store is not supported', |
| 303 | errorTitle, |
| 304 | ) |
| 305 | forEach(units, unit => |
| 306 | on(store, '.reset', unit, () => store.defaultState, errorTitle), |
| 307 | ) |
| 308 | return store |
| 309 | }, |
searching dependent graphs…