React Best Practice to bind checkbox to model

Viewed 112

I'm new to React and I'm having a little trouble to come up with the 'right' way to handle the following situation:

So let's say I'm fetching entities from a backend that contain a boolean value. And I want to show that entities in a React component using a Material UI checkbox. Now when the user checks or unchecks the checkbox I want to update the corresponding entity in the backend immediately.

Pretty simple I thought. So my first approach was to use UseQuery to fetch the data:

    const res = await axios.get<IResourceChange[]>(
      `https://localhost:5001/api/configpicker/resourcechangecollections/${resourceChangeCollectionId}/resourceChanges`
    );
    return res.data;
  };

const {
    data: resourceChanges,
    isLoading: isLoadingResourceChanges,
    error: loadingResourceChangesError,
  } = useQuery<IResourceChange[]>('resourceChanges', fetchResourceChanges);

And then I'm mapping that entities to checkboxes:

resourceChanges?.map((rc) => {
  return (
        <FormControlLabel
          control={
            <Checkbox
              checked={rc.excludeFromExport}
              onChange={() =>
                handleCheckboxChange(
                  rc.resourceChangeID,
                  !rc.excludeFromExport
                )
              }
            />
          }
          label="Exclude from export"
        />
  );
})

And handle the change by sending a PATCH request to the backend:

const handleCheckboxChange = (
    resourceChangeId: number,
    newChecked: boolean
  ) => {
    axios
      .patch(
        `https://localhost:5001/api/configpicker/resourcechanges/${resourceChangeId}`,
        [
          {
            op: 'replace',
            path: '/excludeFromExport',
            value: newChecked,
          },
        ]
      )
      .then((res) => console.log('res :>> ', res));
  };

I'm sure you experts can spot some problems with that. I have a few thoughts how to change this approach, but I couldn't find a guide on what's the best practice to do this.

I have a feeling, that I should replicate the checkbox value in the state, but that seems kind of redundant.

Is there a best practice how to implement this?

0 Answers
Related