3 ms·
I am curious about your approach as I also write my web app in vanilla JS. Where do you store the state or save the data? For me, I use either localstorage for
by richajak 7y ago
I am curious about your approach as I also write my web app in vanilla JS. Where do you store the state or save the data? For me, I use either localstorage for simple update or network fetch for every thing else. For data format, I use Json all the way, rather than handling others,eg FormData, key/value.
- z3t4 7y agoYou want to have a source of truth. For simplicity I use a global variable. I however use Object.defineProperty so that it can only be written to via an "API" (methods on a global object), which is also responsible for calling event listeners. For persistence localStorage works great. But often you want to have the source of truth on the back-end. For example if the user opens the app on two devices A and B, change the background to green on device A, and change the background to red on device B, then open up the app on a third device C, what background should device C get? :) For simplicity I prefer to serialize to JSON, either to localStorage, or a .json file on the server, which is only for persistence in case of a sudden power loss, otherwise data lives in a in-memory object. Clients today is very capable so I like to store as much data on the client as possible for fast reads. Then update that data in the background, which would also fire events (like "newMessage"). For binary blobs however, like images and video, I store them on a server, and let the browser's cache take care of the caching. I sometimes also let the browser cache take care of the caching of .json files if the data is rarely updated. For all static data you can use a high expire date and let the browser handle it. Only use the in app memory for data that is often read/written. If you like to micro-manage the browser cache, you can use service workers. Service workers let you do complicated things like manually updating the cache, upload files from the client to the cache, wake up on push notification to prime the cache, etc. So even if the user is offline when he/she comes back to the web "app" most data is fresh and accessible.