Norbert
Norbert

Reputation: 2771

How to skip initial Apollo query and fetch data on button click?

I have a container in my React / Redux app with multiple mutations and a query:

const MenuWithData = compose(
    graphql(GET_FINAL_CODE_BY_PROJECT_ID, {
        options: ownProps => ({
            variables: {
                id: ownProps.projectId,
            },
            skip: true,
        }),
        props: ({ data }) => data,
    }),
    graphql(DELETE_PROJECT, {
        props: ({ ownProps, mutate }) => ({
            async deleteProject() {
                // ...
            },
        }),
    }),
)(Menu);

export default connect(
    state: ({
        projectId: state.current.projectId,
    }),
    dispatch => ({
        deleteProject(id) {
            dispatch(deleteProject(id));
        },
    })
)(MenuWithData);

The container sends the deleteProject function through the props to the <Menu> component and I call it when a user clicks on the "Delete" button.

I'm trying to do the same thing with the query, but I can't seem to find a way to send it to the component. If I use skip: true, I don't have access to the refetch method, but if I set it to false, then the query executes on load.

Is there a way to execute Apollo queries on events that happen in the component?

Upvotes: 1

Views: 3279

Answers (1)

Daniel Rearden
Daniel Rearden

Reputation: 84687

You should utilize the withApollo HOC instead of graphql:

const MenuWithData = compose(
    withApollo,
    graphql(DELETE_PROJECT, {
        props: ({ ownProps, mutate }) => ({
            async deleteProject() {
                // ...
            },
        }),
    }),
)(Menu);

This will pass your client instance down to the component, so you can do something like this inside your button's click handler:

props.client.query({
  query: GET_FINAL_CODE_BY_PROJECT_ID,
  variables: { id: props.projectId },
}).then(({ data, errors }) => {
  // handle result
})

FWIW, the convention is to never have queries mutate anything -- if calling a query is going to change data, it should be a mutation. Apollo is built around this idea, with the drastically different way queries and mutations are handled by the same HOC.

If you're not firing the query until a user does something, it sounds like your query is potentially mutating data, in which case it may be worth considering making it a mutation in the first place.

Upvotes: 2

Related Questions