Reputation: 1907
I'm trying to update local forage upon any changes to the store.
I know this can be done by this:
import { writable } from "svelte/store";
import localforage from "localforage";
const stored = await localforage.getItem("tasks");
const createTasks = () => {
const { subscribe, set, update } = writable(stored || []);
return {
subscribe,
add: (newTask) => {
update((tasks) => [{ content: newTask }, ...tasks]);
},
};
};
export const tasks = createTasks();
// Is there another way to do this?
tasks.subscribe(async (val) => {
await localforage.setItem("tasks", val);
});
But how can I do this within the createTasks
function instead of tasks.subscribe(...)
.
Follow-up After Answer
It was working for the test snippet above but it's resulting to a "Error: 'bleeps' is not a store with a 'subscribe' method" for the below code.
const createBleeps = async () => {
const { subscribe, update, set } = writable(
(await localforage.getItem("bleeper_bleeps")) || []
);
subscribe(async (val) => {
await localforage.setItem("bleeper_bleeps", val);
});
return {
subscribe,
set,
update: () => update((bleeps) => bleeps),
add: (newBleep) =>
update((bleeps) => [
{
id: uuidv4(),
content: newBleep.content,
interval: newBleep.interval,
prevInterval: null,
intervalID: null,
clickToConfirm: false,
isActive: true,
},
...bleeps,
]),
remove: (bleepId) =>
update((bleeps) => bleeps.filter((bleep) => bleep.id !== bleepId)),
};
};
export const bleeps = createBleeps();
Upvotes: 1
Views: 216
Reputation: 184366
Just move the code into the function:
const createTasks = () => {
const { subscribe, set, update } = writable(stored || []);
subscribe(async (val) => {
await localforage.setItem("tasks", val);
});
return {
subscribe,
add: (newTask) => {
update((tasks) => [{ content: newTask }, ...tasks]);
},
};
};
Upvotes: 2