All files / components/Settings CourseOptionsForm.jsx

100% Statements 11/11
100% Branches 1/1
100% Functions 5/5
100% Lines 10/10

Press n or j to go to the next uncovered block, b, p or k for the previous block.

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60                      234x   234x           234x 11x         234x           234x   234x       652x               11x 11x                          
import React from "react";
import { Form } from "react-bootstrap";
import { toast } from "react-toastify";
import { useBackendMutation } from "main/utils/useBackend";
import {
  courseOptionsQueryKey,
  titleCaseFromOption,
  useCourseOptions,
} from "main/utils/courseOptionsUtils";
 
function CourseOptionsForm({ courseId, canEdit }) {
  const { data: optionsMap = {} } = useCourseOptions(courseId);
 
  const objectToAxiosParams = ({ option, enabled }) => ({
    url: "/api/course/options",
    method: "POST",
    params: { courseId, option, enabled },
  });
 
  const onSuccessOptionUpdated = (data, variables) => {
    toast(
      `${titleCaseFromOption(variables.option)} set to ${data[variables.option]}`,
    );
  };
 
  const courseOptionMutation = useBackendMutation(
    objectToAxiosParams,
    { onSuccess: onSuccessOptionUpdated },
    [courseOptionsQueryKey(courseId)],
  );
 
  const entries = Object.entries(optionsMap);
 
  return (
    <div data-testid="CourseOptionsForm">
      <h5 className="mt-4">Course Options</h5>
      {entries.map(([option, enabled]) => (
        <Form.Check
          key={option}
          id={`course-option-${option}`}
          type="switch"
          label={titleCaseFromOption(option)}
          checked={enabled}
          disabled={!canEdit}
          onChange={(event) => {
            const enabled = event.target.checked;
            courseOptionMutation.mutate({
              option,
              enabled,
            });
          }}
          data-testid={`CourseOptionsForm-toggle-${option}`}
        />
      ))}
    </div>
  );
}
 
export default CourseOptionsForm;