Skip to content
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

Fix upsert #2669

Merged
merged 2 commits into from
Sep 4, 2022
Merged
Show file tree
Hide file tree
Changes from all 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
5 changes: 3 additions & 2 deletions packages/toolkit/src/query/core/buildSlice.ts
Original file line number Diff line number Diff line change
Expand Up @@ -136,7 +136,8 @@ export function buildSlice({
extraReducers(builder) {
builder
.addCase(queryThunk.pending, (draft, { meta, meta: { arg } }) => {
if (arg.subscribe) {
const upserting = isUpsertQuery(arg)
if (arg.subscribe || upserting) {
// only initialize substate if we want to subscribe to it
draft[arg.queryCacheKey] ??= {
status: QueryStatus.uninitialized,
Expand All @@ -148,7 +149,7 @@ export function buildSlice({
substate.status = QueryStatus.pending

substate.requestId =
isUpsertQuery(arg) && substate.requestId
upserting && substate.requestId
? // for `upsertQuery` **updates**, keep the current `requestId`
substate.requestId
: // for normal queries or `upsertQuery` **inserts** always update the `requestId`
Expand Down
35 changes: 35 additions & 0 deletions packages/toolkit/src/query/tests/optimisticUpserts.test.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,41 @@ describe('basic lifecycle', () => {
onSuccess.mockReset()
})

test('Does basic inserts and upserts', async () => {
const newPost: Post = {
id: '3',
contents: 'Inserted content',
title: 'Inserted title',
}
const insertPromise = storeRef.store.dispatch(
api.util.upsertQueryData('post', newPost.id, newPost)
)

await insertPromise

const selectPost3 = api.endpoints.post.select(newPost.id)
const insertedPostEntry = selectPost3(storeRef.store.getState())
expect(insertedPostEntry.isSuccess).toBe(true)
expect(insertedPostEntry.data).toEqual(newPost)

const updatedPost: Post = {
id: '3',
contents: 'Updated content',
title: 'Updated title',
}

const updatePromise = storeRef.store.dispatch(
api.util.upsertQueryData('post', updatedPost.id, updatedPost)
)

await updatePromise

const updatedPostEntry = selectPost3(storeRef.store.getState())

expect(updatedPostEntry.isSuccess).toBe(true)
expect(updatedPostEntry.data).toEqual(updatedPost)
})

test('success', async () => {
const { result } = renderHook(
() => extendedApi.endpoints.test.useMutation(),
Expand Down