#Items in LocalStorage get disappeared after reloading the page.
32 messages · Page 1 of 1 (latest)
i am building a shopping cart in nextJs. It works fine, ie: when i add items to the cart, it works, and the items are added to the LocalStorage but when i manualy reload the page, the items in the LocalStorage get disappeared
Bceause you overwrite the storage with the initial value on mount.
Your useEffect runs initially and overwrites the currently stored value.
You can fix it by reading the initial value from localStorage and then falling back to the explicit initial value passed as an argument.
can you show me an example?
You can just use a commonly used hook instead of reinventing the wheel
Persist the state with local storage so that it remains after a page refresh. This can be useful for a dark theme.
This hook is used in the same way as…
it works but gives hydration error
btw i used https://usehooks.com/useLocalStorage/
Warning: Text content did not match. Server: "0" Client: "2"
Added 2 items to the cart, upon reloading the page, it throws hydration error
Because you cannot use the local storage in server-side code and thus it renders a different result.
You have to disable SSR for that component or page if you don't use server-side shopping carts.
is there any other simpler way to do this?
Not really.
const useLocalStorage = dynamic(()=> import("src/hooks/useLocalStorage"), {
ssr: false
})
i found this
but im getting error under the import("...")
Argument of type '() => Promise<typeof import("e:/projects/productbox-test/src/hooks/useLocalStorage")>' is not assignable to parameter of type 'DynamicOptions<{}> | Loader<{}>'.
this only works for components
a custom hook is not a component?
fixed it, tysm
also, can you tell me how would I upload products? I have a file where I have added the dummy data of products. And I want to add a form where I would be able to upload the product, and the product needs to be saved in the items.ts
That's not going to work. You need a persistent data source like a database.
oh, but i was assigned a task by someone and he mentioned to upload a product.
But you can't alter the source code on the server-side.
You need to store products in a database and query those.
- You should be able to add items through the front end application
- A list of all the items on the items page
- The checkout page should have all the items that you chose to checkout
- The number of items in cart is persistant amongst different browser tabs
Decent design/layout of content
I was asked for these, where I have acheived 3 of them
should i just submit and tell him that the 1st one requires knowledge of DB?