Skip to content

typeDefinition of updater function in setQueryData #506

Closed
@TkDodo

Description

@TkDodo

Hi,

First of all: thanks for this 😎 library. I'm having a quick typescript question:

setQueryData takes an updater in the form of:

((oldData: T | undefined) => T)

The question is: if oldData is possibly undefined, how would be we able to construct T?

suppose we have a simple type:

type Person = {
    firstName: string,
    lastName: string
}

and we mutate that persons firstName, which we want to optimistically update (I've taken the optimistic update example as a base):

useMutation(
    firstName => axios.patch('/api/person', { firstName }),
    {
      onMutate: firstName => {
        queryCache.cancelQueries('person')

        const previousValue = queryCache.getQueryData('person')

        queryCache.setQueryData('person', old => ({
          ...old,
          firstName
        }))

        return previousValue
      }
  )

but if oldData is possibly undefined, the resulting object can never be of type Person - it might miss the lastName.

We are currently working around this by doing:

const previousValue = queryCache.getQueryData('person')

if (previousValue) {
    queryCache.setQueryData('person', {
        ...previousValue,
        firstName
    })
}

The question is: can old really be undefined ? If so, wouldn't this be a runtime error in the example here when accessing old.items ? Or is this maybe just an issue with the type definitions and old can actually never be undefined?

Thanks for clarifying

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions