72 lines
2.6 KiB
TypeScript
72 lines
2.6 KiB
TypeScript
![]() |
import {create} from "zustand";
|
||
|
import {persist} from "zustand/middleware";
|
||
|
import {quizStore} from "@root/quizes";
|
||
|
import {useParams} from "react-router-dom";
|
||
|
|
||
|
interface QuestionStore {
|
||
|
listQuestions: { [key: number]: any};
|
||
|
updateQuestionsList: (id: number, values: unknown) => void;
|
||
|
removeQuestion: (id: number) => void;
|
||
|
createBlankQuestions: () => void;
|
||
|
}
|
||
|
|
||
|
export const questionStore = create<QuestionStore>()(
|
||
|
|
||
|
persist(
|
||
|
(set, get) => ({
|
||
|
listQuestions: {
|
||
|
},
|
||
|
|
||
|
updateQuestionsList: (id: number, values: any) => {
|
||
|
const state = get()["listQuestions"] || {};
|
||
|
state[id] = {
|
||
|
...state[id],
|
||
|
...values
|
||
|
};
|
||
|
set({listQuestions: state});
|
||
|
},
|
||
|
removeQuestion: (id) => {
|
||
|
const state = get()["listQuestions"] || {};
|
||
|
|
||
|
const newState = Object.entries(state).reduce<any>((accumulator, [key, value], index, array) => {
|
||
|
if (key !== id.toString()) {
|
||
|
accumulator[key] = value;
|
||
|
}
|
||
|
return accumulator;
|
||
|
}, {});
|
||
|
set({listQuestions: newState});
|
||
|
},
|
||
|
createBlankQuestions: () => {
|
||
|
const newListQuestions = get()["listQuestions"] || {};
|
||
|
const id = getRandom(1000000, 10000000)
|
||
|
newListQuestions[id] = {
|
||
|
"id": id,
|
||
|
//"quiz_id": listQuizes.id, // id опроса, к которому вопрос принадлежит
|
||
|
"title": "", // заголовок вопроса
|
||
|
"description": "", // развёрнутое описание вопроса
|
||
|
"type": "", // button, text, select, checkbox, file, none
|
||
|
"required": true,
|
||
|
"deleted": true,
|
||
|
"page": 0,
|
||
|
"content": "",
|
||
|
"version": 0,
|
||
|
"parent_ids": [
|
||
|
0
|
||
|
],
|
||
|
"created_at": "",
|
||
|
"updated_at": ""
|
||
|
};
|
||
|
set({listQuestions: newListQuestions});
|
||
|
return id;
|
||
|
}
|
||
|
}),
|
||
|
{
|
||
|
name: "question",
|
||
|
}
|
||
|
)
|
||
|
);
|
||
|
function getRandom(min: number, max: number) {
|
||
|
min = Math.ceil(min);
|
||
|
max = Math.floor(max);
|
||
|
return Math.floor(Math.random() * (max - min)) + min;
|
||
|
}
|