Alex Kor
Alex Kor

Reputation: 85

Getting the type error while selecting Values from Result of Query

I was writing the logic of selecting Values from a Result of the Query and I faced an error. I tried to tackle it by myself, but end up with no success.

What I did:

I got from the query an array of objects.

There is the array of what was got:

[
 {
 chosenDoughType: "Thin"
 chosenSize: 26
 doughTypes: (2) [{…}, {…}]
 id: "yHYRVvZlnAZ6jXG9kzI4B"
 pizzaId: "fMtMxzIkRTsHEwHsSvGvi"
 sizes: (3) [{…}, {…}, {…}]
 },
// and a couple more similar
]

And there is my code where I wanted to get the only one object with a specific id:

interface SpecType {
    id: string
    doughTypes: object[]
    sizes: object[]
    chosenDoughType: string
    chosenSize: number
    pizzaId: string
}
  const { oneSpecData, isLoading, isSuccess, isError } = useGetSpecsQuery(undefined, {
        selectFromResult: result => ({
            ...result,
            oneSpecData: result.filter((item: SpecType): boolean => {
                return item.id !== specId
            }),
        }),
    })

but I received this message error:

TS2339: Property 'filter' does not exist on type 'UseQueryStateDefaultResult<QueryDefinition<void, BaseQueryFn<string | FetchArgs, unknown, FetchBaseQueryErr
or, {}, FetchBaseQueryMeta>, never, SpecType[], "api">>'.
  Property 'filter' does not exist on type '{ error?: undefined; data?: undefined; fulfilledTimeStamp?: undefined; originalArgs?: undefined; requestId?: unde
fined; endpointName?: string | undefined; startedTimeStamp?: undefined; status: QueryStatus.uninitialized; ... 5 more ...; isUninitialized: true; } & { ...; 
}'.
    55 |         selectFromResult: result => ({
    56 |             ...result,
  > 57 |             oneSpecData: result.filter((item: SpecType): boolean => {
       |                                 ^^^^^^
    58 |                 return item.id !== specId
    59 |             }),
    60 |         }),

I guess the problem is in typification, but I do not know how to tackle it to make my code work.

Upvotes: 0

Views: 761

Answers (1)

phry
phry

Reputation: 44236

result here is the full result. With data, isSuccess and all the other properties.

You probably want to do something like

selectFromResult: result => ({
    ...result,
    data: { ...data, oneSpecData: result.data.something.filter((item: SpecType): boolean => {
        return item.id !== specId
    }),
    }

}),

but keep in mind that this will return a new object in data on every render and not a stable reference - that might lead to your application rerendering a lot more often than you'd like.

You could do better with a selector like

const selector = useCallback(data => ({
  ...data, 
  oneSpecData: data.something.filter((item: SpecType) item.id !== specId)
  }), [specId])


selectFromResult: result => ({
    ...result,
    data: selector(data)
}),

Upvotes: 1

Related Questions