How to use Apollo Client's useQuery and useMutation Hooks with Ant Design Forms

Viewed 521

In our web application, we use React with Apollo Graphql. As it is recommended in the apollo docs, we want to use the useQuery and useMutation hooks to communicate with the backend server.

Our app works roughly like this: We import a excel-file, parse it in the frontend, send the resulting javascript objects via graphql to the backend and save them in the mongodb database. In the frontend, we have some forms containing the excel content. After we make some changes, we can save and overwrite the data in the database. In the end, a new excel can be exported from the database data.

import { Form } from "antd";

export default () => {
  const [form] = Form.useForm();
  const [exelId, setExcelId] = useState("");

  const [saveData] = useMutation(SAVEDATA, {
    onCompleted: ({ dataFromDB }) => {
      form.setFieldsValue(dataFromDB);
    },
  });
  const { data: _ } = useQuery(GETDATA, {
    skip: !exelId,
    onCompleted: ({ dataFromDB }) => {
      form.setFieldsValue(dataFromDB);
    },
  });

  const onFinish = (formValues) => {
    saveData({ variables: { formValues } });
  };

  return (
    <Form form={form} onFinish={onFinish}>
      <ExcelUpload saveData={saveData} setExcelId={setExcelId} />
      <SomeForms />
      <Button type="primary">Save</Button>
    </Form>
  );
};

The problem with our current code is that it causes unnecessary network traffic: After uploading a excel-file, I start a mutation, which returns the required data and sets an "excelId" state. This trigger then the query which fetches the same data. However, I need this query if i reload the page or want to load different data from the database.

I think there are two ways to solve this:

1. Don't use the useMutation hook for filling the form: That would be easy to implement as I don't have to distinguish between fetching data after an excel-upload or fetching existing data from the data base. But I still need a mutation AND a query.

2. Don't start a query in the excel-uploading process, as the data is received via the mutation: I think that is complicated to implement with Apollo Client hooks and not the intended way how to use the useQuery hook.

Is there some kind of best practices, how to use the Apollo Client hooks in similar scenarios? I thought that using those hooks should simplify things, e. g. using the useQuery hook can serve as state. However, using ant design form we also have this form state, which we have to manually set and read with "form.setFieldsValue()" and "form.getFieldsValue()". Is there a good way to combine those with useQuery?

0 Answers
Related