Search code examples
react-nativereduxrtk-query

How to throw Error to RTK Query useQuery() hook from onCacheEntryAdded lifecycle callback


I would like to indicate that socket disconnected by throwing an error to useQuery() hook so the error is accessible from "error" here:

const [query, { isSuccess, data, error }] = useQuery()

Mu use query hook is pretty regular with onCacheEntryAdded lifecycle callback:

async onCacheEntryAdded() {
        socket.on('disconnect', reason => {
          // Throw error
        })
        ...
}

I haven't found any answers to this on the internet, but the problem looks very obvious.


Solution

  • You cannot. This is a lifecycle event that executes after the query is finished - and the query cannot jump into an error state outside of the base Promise it works on. You could change the shape of the "data" of the query to include an error field and use updateQueryData to set that.