Skip to content

Commit

Permalink
feat: offline mutations
Browse files Browse the repository at this point in the history
move reducer into Mutation class to avoid passing state (and options) around
  • Loading branch information
TkDodo committed Dec 4, 2021
1 parent 4b75108 commit 0b7d6ef
Showing 1 changed file with 57 additions and 58 deletions.
115 changes: 57 additions & 58 deletions src/core/mutation.ts
Original file line number Diff line number Diff line change
Expand Up @@ -291,7 +291,7 @@ export class Mutation<
}

private dispatch(action: Action<TData, TError, TVariables, TContext>): void {
this.state = reducer(this.state, action)
this.state = this.reducer(action)

notifyManager.batch(() => {
this.observers.forEach(observer => {
Expand All @@ -304,6 +304,62 @@ export class Mutation<
})
})
}

private reducer(
action: Action<TData, TError, TVariables, TContext>
): MutationState<TData, TError, TVariables, TContext> {
switch (action.type) {
case 'failed':
return {
...this.state,
failureCount: this.state.failureCount + 1,
}
case 'pause':
return {
...this.state,
isPaused: true,
}
case 'continue':
return {
...this.state,
isPaused: false,
}
case 'loading':
return {
...this.state,
context: action.context,
data: undefined,
error: null,
isPaused: false,
status: 'loading',
variables: action.variables,
}
case 'success':
return {
...this.state,
data: action.data,
error: null,
status: 'success',
isPaused: false,
}
case 'error':
return {
...this.state,
data: undefined,
error: action.error,
failureCount: this.state.failureCount + 1,
isPaused: false,
status: 'error',
}
case 'setState':
return {
...this.state,
...action.state,
}
default:
return this.state
}
}
}

export function getDefaultState<
Expand All @@ -322,60 +378,3 @@ export function getDefaultState<
variables: undefined,
}
}

function reducer<TData, TError, TVariables, TContext>(
state: MutationState<TData, TError, TVariables, TContext>,
action: Action<TData, TError, TVariables, TContext>
): MutationState<TData, TError, TVariables, TContext> {
switch (action.type) {
case 'failed':
return {
...state,
failureCount: state.failureCount + 1,
}
case 'pause':
return {
...state,
isPaused: true,
}
case 'continue':
return {
...state,
isPaused: false,
}
case 'loading':
return {
...state,
context: action.context,
data: undefined,
error: null,
isPaused: false,
status: 'loading',
variables: action.variables,
}
case 'success':
return {
...state,
data: action.data,
error: null,
status: 'success',
isPaused: false,
}
case 'error':
return {
...state,
data: undefined,
error: action.error,
failureCount: state.failureCount + 1,
isPaused: false,
status: 'error',
}
case 'setState':
return {
...state,
...action.state,
}
default:
return state
}
}

0 comments on commit 0b7d6ef

Please sign in to comment.