Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call an apollo client query from a redux action

Tags:

react-apollo

If I'm using redux and the apollo client in my app, what's the best way to trigger a query from an action outside of a component.

For example, if I have a standard app, with redux and apollo client configured, how should I trigger a "refresh" list. I can trigger a function on the component itself which has the gql, but how would I do it from an action which would be more in line with flux.

import React, { Component, PropTypes } from 'react';
import { graphql } from 'react-apollo';
import gql from 'graphql-tag';
import { connect } from 'react-redux';
import { refreshProfile } from './actions';

class Profile extends Component { ... }
Profile.propTypes = {
  data: PropTypes.shape({
    loading: PropTypes.bool.isRequired,
    user: PropTypes.object,
  }).isRequired,
};

const UserQuery = gql`
  query getUser {
    user {
      id
      name
    }
  }
`;

const ProfileWithData = graphql(UserQuery)(Profile); 
const ProfileWithDataAndState = connect(
 (state) => ({ user: state.user })),
 )(ProfileWithData);

And, say I want to trigger an action to refresh that user data? Since the logic is in the component itself, I'm not sure how I would trigger that gql query from the action itself.

like image 357
MonkeyBonkey Avatar asked Nov 23 '16 17:11

MonkeyBonkey


People also ask

Can you use Apollo Client with Redux?

Every Apollo client creates its own internal Redux Store to manage queries and their results. It eases the use of Redux Dev Tools.

How do you use Apollo and Redux together?

If you want to use your Redux and Apollo state in a component, you need to use both graphql from react-apollo and connect from react-redux. This will let you better track the different events that happen in your app, and how your client and server side data changes interleave.

Does Apollo Client use React query?

Apply the useQuery hookWe'll use Apollo Client's useQuery React Hook to execute our new query within the Launches component. The hook's result object provides properties that help us populate and render our component throughout the query's execution.

Can I use Apollo Client without React?

To use Apollo in a vanilla JS project, you instead need to use the entry point @apollo/client/core : import { ApolloClient, gql, InMemoryCache } from "@apollo/client/core"; This is documented, but was a little hard to find within the Apollo 3.0 migration guide.


1 Answers

I would need to use the ApolloClient in my actions.js. e.g.

import ApolloClient, { createNetworkInterface } from 'apollo-client';
const networkInterface = createNetworkInterface({
  uri: config.graphCoolUri,
});

const client = new ApolloClient({
  networkInterface,
  dataIdFromObject: r => r.id,
});

const { data } = await client.query({
   query: UserQuery
});
like image 197
MonkeyBonkey Avatar answered Jan 02 '23 11:01

MonkeyBonkey