Akshay Vijay Jain
Akshay Vijay Jain

Reputation: 15945

What is equivalent of useQueryState for a redux toolkit mutation?

You can get data from redux store using the redux toolkit hook useQueryState
https://redux-toolkit.js.org/rtk-query/api/created-api/hooks#usequerystate

const useQueryStateResult = api.endpoints.getPosts.useQueryState(arg, options)

this property .useQueryState exists only for queries, what to use if we want to know the result of mutation later on?

Upvotes: 1

Views: 1835

Answers (1)

Quoc An Ha
Quoc An Ha

Reputation: 1

I encountered this question for a usecase where a POST request returns the id of a newly created entity.

I solved it crudely by selecting the api state itself:

const last = useAppSelector(state => {
    return Object.values(state.api.mutations).reduce((acc, val) => {
        if(val?.endpointName === "ENDPOINT_NAME") {
            if(!acc || !acc.fulfilledTimeStamp) {
                return val;
            } else {
                if(val.fulfilledTimeStamp && val.fulfilledTimeStamp > acc.fulfilledTimeStamp) {
                    return val;
                }
            }
        }
        return acc;
    }, undefined);
});

There's a lot of optimization possible still, such as also considering startedTimestamp, other conditions, and could also be written using more consisely more shorthands.

Upvotes: 0

Related Questions