How to switch from a normal writable
store to persisted
?
#234
-
I am trying to use persistent storage for one of my Svelte stores but I don't have enough knowledge to get it working. Below is my current store setup, help to switch it to using persisted would be greatly appreciated!!
export const cartItems = writable<CartItem[]>([]);
export const addToCart = (id: string) => {
let items = get(cartItems);
let itemPosition = items.findIndex(
(item) => { return item.id == id }
)
if (itemPosition !== -1) {
cartItems.update(() => {
let updatedItems = items.map( (item) => {
if (item.id === id) {
return { ...item, quantity: item.quantity + 1 };
}
return item;
});
return updatedItems;
})
} else {
cartItems.update(() => {
return [ ...items, { id: id, quantity: 1 } ]
})
}
}
export const removeFromCart = (id: string) => {
let items = get(cartItems);
let itemPosition = items.findIndex(
(item) => { return item.id == id }
)
if (items[itemPosition]?.quantity - 1 === 0) {
items.splice(itemPosition, 1)
}
cartItems.update(() => {
let updatedItems = items.map((item) => {
if (item.id === id) {
return { ...item, quantity: item.quantity -1 }
}
return item;
});
return updatedItems;
})
}
declare class CartItem {
id: string
quantity: number
} |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 21 replies
-
Hi Jasper! No worries, it's super easy to do. First, install the pnpm install -D svelte-persisted-store Then, import the package at the top of your file. import { persisted } from 'svelte-persisted-store' Now all you have to do is switch your code on line 1 from Note: ---export const cartItems = writable<CartItem[]>([]);
+++export const cartItems = persisted<CartItem[]>('cart', []); Now, if you open DevTools -> Application -> Local Storage, you should see the cart data. I hope that helps! Let me know if you have any further questions |
Beta Was this translation helpful? Give feedback.
Good news i have resolved the issue.
In productCard.svelte i very simply needed to move
export let product
to the top of the script!