frontPanel/src/stores/questions.ts
2023-08-10 16:45:44 +03:00

84 lines
2.2 KiB
TypeScript

import { create } from "zustand";
import { persist } from "zustand/middleware";
import { quizStore } from "@root/quizes";
import { useParams } from "react-router-dom";
export type Question = {
title: string;
description: string;
type: string;
required: boolean;
deleted: boolean;
page: number;
content: string;
version: number;
parent_ids: number[];
created_at: string;
updated_at: string;
};
interface QuestionStore {
listQuestions: Record<number, Question[]>;
setQuestions: (id: number, questions: Question[]) => void;
updateQuestionsList: (id: number, index: number, values: unknown) => void;
removeQuestion: any;
createQuestion: (id: number) => void;
}
export const questionStore = create<QuestionStore>()(
persist(
(set, get) => ({
listQuestions: {},
setQuestions: (id: number, questions: Question[]) => {
const listQuestions = get()["listQuestions"];
set({ listQuestions: { ...listQuestions, [id]: questions } });
},
updateQuestionsList: (id: number, index: number, values: any) => {
const array = get()["listQuestions"][id] || [];
array[index] = {
...array[index],
...values,
};
const state = get()["listQuestions"] || {};
state[id] = array;
console.log(state);
set({ listQuestions: state });
},
createQuestion: (id: number) => {
const array = get()["listQuestions"][id] || [];
array.push({
title: "",
description: "",
type: "",
required: true,
deleted: true,
page: 0,
content: "",
version: 0,
parent_ids: [0],
created_at: "",
updated_at: "",
});
const state = get()["listQuestions"] || {};
state[id] = array;
set({ listQuestions: state });
},
removeQuestion: (id: number, index: number) => {
const array = get()["listQuestions"][id] || [];
array.splice(index, 1);
const state = get()["listQuestions"] || {};
state[id] = array;
set({ listQuestions: state });
},
}),
{
name: "question",
}
)
);