reactjsreact-apolloreact-apollo-hooks

How to use the Apollo client directly in a React child component


I have a Toolbar component rendered by an App component, I want to do some api-call update when a toolbar button is clicked eg. 'save'.

index.js:

ReactDOM.render(
  <BrowserRouter>
    <ApolloProvider client={client}>
        <App />
    </ApolloProvider>
  </BrowserRouter>,
  document.getElementById('root')
)

App.js

function App(props) {

  return (
    <div className="App">      
      <div>
        <Toolbar />
      </div>
    </div>
  )

I know how to handle the button click in the toolbar and how to pass props and handlers up and down the tree so that doesn't worry me but I actually want to access the Apollo 'client' object directly in a child component - something along these lines (eg. in Toolbar):

const saveButtonClicked = (() => {

  client
    .query({...my query info...})
    .then(response => 
      {
        //Update was done
      })
})

I have used the client in other components using the useQuery hook but this expects to return render/JSX data, I just want to run a query. My understanding is that the 'client' object is held in context somewhere but I don't know how to get a reference to it so I guess what I'm asking is how do I access the 'client' object outside of a hook?


Solution

  • You can use the withApollo higher order component to put the client into the props of your component.

    import { withApollo } from '@apollo/react-hoc';    
    
    const MyComponent = ({ client }) => {
      ...
    }
    export default withApollo(MyComponent)
    

    Here is a link to the docs https://www.apollographql.com/docs/react/api/react-hoc/#withapollocomponent