Skip to content

Instantly share code, notes, and snippets.

@hand-dot
Created September 6, 2023 03:42
Show Gist options
  • Select an option

  • Save hand-dot/770b583c99c208669d863b9004768d3f to your computer and use it in GitHub Desktop.

Select an option

Save hand-dot/770b583c99c208669d863b9004768d3f to your computer and use it in GitHub Desktop.
Wix TODO app
import wixData from "wix-data";
import { local } from "wix-storage";
// データベースへの処理
const tasksDB = {
create: (task) => wixData.insert("Tasks", task),
readByUserId: (userId) => wixData.query("Tasks").eq("userId", userId).find(),
update: (task) => wixData.update("Tasks", task),
deleteByIds: (ids) => wixData.bulkRemove("Tasks", ids),
};
$w.onReady(async function () {
// 要素の取得
const loading = $w("#loading");
const titleInput = $w("#titleInput");
const addBtn = $w("#addBtn");
const clearBtn = $w("#clearBtn");
const tasksRpt = $w("#tasksRpt");
// userId を生成 or 設定する
let userId = local.getItem("userId");
if (!userId) {
userId = crypto.randomUUID();
local.setItem("userId", userId);
}
// tasksRpt とデータの紐付けを行う
tasksRpt.onItemReady(($item, itemData) => {
$item("#taskTitle").text = itemData.title;
$item("#taskBtn").label = itemData.completed ? "V" : "";
$item("#taskBtn").onClick(async (e) => {
itemData.completed = !itemData.completed;
e.target.label = itemData.completed ? "V" : "";
loading.show();
await tasksDB.update(itemData);
loading.hide();
});
});
// addBtn を押した時の処理を書く
addBtn.onClick(async () => {
if (!titleInput.value) return;
loading.show();
await tasksDB.create({ title: titleInput.value, completed: false, userId });
titleInput.value = "";
const myTasks = (await tasksDB.readByUserId(userId)).items;
tasksRpt.data = myTasks;
loading.hide();
});
// clearBtn を押した時の処理を書く
clearBtn.onClick(async () => {
// 削除したいタスクのIDを取得(配列)
const idsToRemove = tasksRpt.data
.filter((t) => t.completed)
.map((t) => t._id);
loading.show();
await tasksDB.deleteByIds(idsToRemove);
const myTasks = (await tasksDB.readByUserId(userId)).items;
tasksRpt.data = myTasks;
loading.hide();
});
// tasksRpt へデータを設定する処理を書く
// userId を使って自分のタスクのみを取得する
const myTasks = (await tasksDB.readByUserId(userId)).items;
tasksRpt.data = myTasks;
loading.hide();
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment