Skip to content

Commit 887cb2a

Browse files
authored
fix: (react) explicitly overwrite error variable in state (#3860)
1 parent 917ac60 commit 887cb2a

3 files changed

Lines changed: 48 additions & 0 deletions

File tree

.changeset/bright-jobs-shout.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'urql': patch
3+
---
4+
5+
don't persist error state of old gql responses after refetch in react state
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
import { it, expect, describe } from 'vitest';
2+
import { computeNextState, initialState } from './state';
3+
4+
describe('computeNextState', () => {
5+
it('clears error when new result does not include an error key', () => {
6+
const prevState = { ...initialState, error: new Error('old error') };
7+
const result = { fetching: false };
8+
const newState = computeNextState(prevState, result);
9+
expect(newState.data).toBeUndefined();
10+
expect(newState.error).toBeUndefined();
11+
expect(newState.fetching).toBe(false);
12+
});
13+
14+
it('preserves error when new result is still fetching', () => {
15+
const error = new Error('old error');
16+
const prevState = { ...initialState, error };
17+
const result = { fetching: true };
18+
const newState = computeNextState(prevState, result);
19+
expect(newState.data).toBeUndefined();
20+
expect(newState.error).toBe(error);
21+
expect(newState.fetching).toBe(true);
22+
});
23+
24+
it('sets error when new result has an error', () => {
25+
const error = new Error('something went wrong');
26+
const result = { fetching: false, error };
27+
const newState = computeNextState(initialState, result as any);
28+
expect(newState.data).toBeUndefined();
29+
expect(newState.error).toBe(error);
30+
expect(newState.fetching).toBe(false);
31+
});
32+
33+
it('preserves data when result has no data and no error', () => {
34+
const data = { foo: 1 };
35+
const prevState = { ...initialState, data };
36+
const result = { fetching: false };
37+
const newState = computeNextState(prevState, result);
38+
expect(newState.data).toBe(data);
39+
expect(newState.error).toBeUndefined();
40+
expect(newState.fetching).toBe(false);
41+
});
42+
});

packages/react-urql/src/hooks/state.ts

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -55,6 +55,7 @@ export const computeNextState = <T extends Stateish>(
5555
result.data !== undefined || result.error ? result.data : prevState.data,
5656
fetching: !!result.fetching,
5757
stale: !!result.stale,
58+
error: result.fetching ? prevState.error : result.error,
5859
};
5960

6061
return isShallowDifferent(prevState, newState) ? newState : prevState;

0 commit comments

Comments
 (0)