Untitled

mail@pastecode.io avatar
unknown
typescript
2 months ago
2.8 kB
2
Indexable
Never
  // Get selected option ids from cache data
  const requiredSelectedOptionsCount: number = Number(
    /Click on (\d+) answers/.exec(sectionStepNumberData.question_text)![1],
  );
  const [activedQuestionOptionIds, setActivedQuestionOptionIds] = useState<
    number[]
  >([]);
  useEffect(() => {
    if (fetchTestQuestionOptions.isSuccess) {
      const selectedOptionIds = fetchTestQuestionOptions.data
        .filter((questionOption) => questionOption.is_selected)
        .map((questionOption) => questionOption.id);
      setActivedQuestionOptionIds(selectedOptionIds);
    }
  }, [fetchTestQuestionOptions.isSuccess]);

  // Handle select question option
  const mutationAnswerTestQuestionOptions = useMutation({
    mutationKey: queryKeyTestQuestionOptions,
    mutationFn: async (selectedOptionId: number) => {
      // Toggle selected option id in actived question option ids [maximal selected options count = requiredSelectedOptionsCount]
      setActivedQuestionOptionIds((prev) => {
        const isOptionSelected = prev.includes(selectedOptionId);
        if (isOptionSelected) {
          return prev.filter((id) => id !== selectedOptionId);
        }
        if (prev.length < requiredSelectedOptionsCount) {
          return [...prev, selectedOptionId];
        }
        return prev;
      });
      // If actived options selected length === requiredSelectedOptionsCount ===> set to cache data and send to api
      const isAllRequiredOptionsSelected =
        activedQuestionOptionIds.length === requiredSelectedOptionsCount - 1;
      if (isAllRequiredOptionsSelected) {
        console.log(
          activedQuestionOptionIds.length,
          requiredSelectedOptionsCount,
        );

        // Toggle selected option in options data
        const newOptions = fetchTestQuestionOptions.data!.map(
          (questionOption) => ({
            ...questionOption,
            is_selected: activedQuestionOptionIds.includes(questionOption.id),
          }),
        );
        // Active selected option in cache data
        queryClient.setQueryData(queryKeyTestQuestionOptions, newOptions);
        // Send selected option ids to api
        const extractSelectedOptionIds = newOptions
          .filter((option) => option.is_selected)
          .map((option) => option.id);
        await APIanswerTestQuestion({
          testName: testUrlParams.testName,
          sectionId:
            atomStateTestData.sections[testUrlParams.sectionNumber - 1]!.id,
          questionId: sectionStepNumberData.id,
          selectedOptionIds: extractSelectedOptionIds,
        });
      }
    },
  });
  const handleSelectQuestionOption = (selectedOptionId: number) => {
    mutationAnswerTestQuestionOptions.mutate(selectedOptionId);
  };
Leave a Comment