Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using react-apollo, how to define 2 mutations in the same component with TypeScript?

Using the following issue on GitHub I am able to make one mutation work with Typescript. But I did not find a way to use 2 mutations in the same component.

There is only one mutate() function in this.props.

How must we typed our component to make it understand the name options passed to graphql?

graphql<ContainerProps, {}, string, ContainerProps>(gql`... `, { name: 'deleteData' });
graphql<ContainerProps, {}, string, ContainerProps>(gql`...`, { name: 'createData' });

EDIT: If the 2 mutations have the same parameter name (a string named id for example), do we really need to wrap these parameters in an explicit type?

EDIT 2: I have this exception when I declare the 2 mutations with { name: 'xxx' }:

TypeError: _this.props.mutate is not a function

If I declare only one mutation (without the name option), it's working properly.

like image 510
pellea Avatar asked Aug 22 '26 20:08

pellea


1 Answers

Based on the link provided by Miro Lehtonen here is what's working for me.

type MutationProps = {
    create: MutationFunc<IResponse, ICreateVariables>;
    delete: MutationFunc<IResponse, IDeleteVariables>;
};

type ContainerProps = OtherQueryProps & MutationProps;

const withCreate =
    graphql<ContainerProps, IResponse, ICreateVariables, ContainerProps>(
        CreateMutation,
        {
            // tslint:disable-next-line:no-any
            props: ({ mutate, ...rest }): any => ({
                ...rest,
                create: mutate
            })
        });

The code is the same for the delete mutation.

The code is working but I don't like having any in it. I did not find a way to correctly type the props and I don't think I return the correct type (though it's working fine). Any suggestions are very welcome (on how to remove the any).

like image 152
pellea Avatar answered Aug 24 '26 09:08

pellea