I want to wrap all my API calls in redux so that I can dispatch these api functions wherever I use inside react components. As I know RSK pass Apollo client as a context property of the component, but how can use it in my redux actions?
@gijoncheng
As the Apollo client is saved as 'client' within the context variable, and redux-thunk middleware enabled within the redux store, you may call your GraphQL queries in the following way.
function foo(bar) {
return async (dispatch, getState, { client }) => {
const request = await client.query({
query: someQuery,
variables: {
input: bar
}
});
const result = await request;
dispatch({
type: DEFAULT_ACTION,
payload: result
})
}
}
To be able to use Apollo client in redux-thunk actions, pass is as an extra argument to thunk while creating the store.
export const client = new ApolloClient({
link: createHttpLink({ uri: `${apiUrl}/graphql` })
),
cache: new InMemoryCache()
});
const store = createStore(
rootReducer,
initialState,
applyMiddleware(thunk.withExtraArgument(client)),
)
);
Then you will be able to use it in your actions easly.
export const getCartAction = () => (
dispatch,
getState,
client
) => {
dispatch({
type: 'GET_CART_ATTEMPT'
});
client
.query({
query: GET_CART,
fetchPolicy: 'no-cache'
})
.then(res => {
dispatch({
type: 'GET_CART_SUCCESS',
payload: res.data
}
});
});
};
Most helpful comment
@gijoncheng
As the Apollo client is saved as 'client' within the context variable, and redux-thunk middleware enabled within the redux store, you may call your GraphQL queries in the following way.