All files / src/components/views/Schemas SchemaSaves.tsx

0% Statements 0/14
0% Branches 0/13
0% Functions 0/2
0% Lines 0/14

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                                                                                     
import * as React from "react";
import { SertoUiContext, SertoUiContextInterface } from "../../../context/SertoUiContext";
import { SchemaDataInput, SchemaDataResponse } from "./types";
import { SplitButton } from "../../elements/SplitButton";
 
export interface SchemaSavesProps {
  schema: SchemaDataInput | SchemaDataResponse;
}
 
export const SchemaSaves: React.FunctionComponent<SchemaSavesProps> = (props) => {
  const { schema } = props;
  const [isSaved, setIsSaved] = React.useState(!!("favorite" in schema && schema.favorite));
  const [saveCount, setSaveCount] = React.useState(("favoriteCount" in schema && schema.favoriteCount) || 0);
  const [isLoading, setIsLoading] = React.useState(false);
  const schemasService = React.useContext<SertoUiContextInterface>(SertoUiContext).schemasService;
 
  async function onClick() {
    setIsLoading(true);
    try {
      await schemasService.toggleSaveSchema?.(schema.slug);
      setIsSaved(!isSaved);
      // kinda dumb, but mutate isn't working for some reason. maybe toggle save endpoint should return new count. this is good enough.
      setSaveCount(saveCount + (isSaved ? -1 : 1));
    } catch (err) {
      console.error("Failed to (un)save schema:", err);
    }
    setIsLoading(false);
  }
 
  return (
    <SplitButton
      onClick={onClick}
      icon={isSaved ? "Star" : "StarBorder"}
      isLoading={isLoading}
      rightContent={saveCount}
      leftWidth={45}
      disabled={!schemasService.isAuthenticated}
    >
      {!schemasService.isAuthenticated ? "Saves" : isSaved ? "Saved" : "Save"}
    </SplitButton>
  );
};