All files / components/Settings CourseOptionsForm.jsx

100% Statements 10/10
100% Branches 0/0
100% Functions 5/5
100% Lines 9/9

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 61 62 63 64              21x                     21x           21x 4x         21x           21x   21x       24x               4x                          
import React from "react";
import { Form } from "react-bootstrap";
import { toast } from "react-toastify";
import { useBackend, useBackendMutation } from "main/utils/useBackend";
import { titleCaseFromOption } from "main/utils/courseOptionsUtils";
 
function CourseOptionsForm({ courseId, canEdit }) {
  const { data: optionsMap } = useBackend(
    [`/api/course/options/?courseId=${courseId}`],
    {
      // Stryker disable next-line StringLiteral : GET and "" are equivalent mutationss
      method: "GET",
      url: "/api/course/options",
      params: { 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 },
    [`/api/course/options/?courseId=${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) =>
            courseOptionMutation.mutate({
              option,
              enabled: event.target.checked,
            })
          }
          data-testid={`CourseOptionsForm-toggle-${option}`}
        />
      ))}
    </div>
  );
}
 
export default CourseOptionsForm;