简体   繁体   中英

localStorage does not work with user accounts

I'm building an application whereby if a user wishes to add an item to a personal watchlist, they must be logged in. I use localStorage to store this personal watchlist data and to retrieve it. The problem I am having is that if account 'A' adds an item to their watchlist and then logs out and account 'B' then logs in, the previous stored data is returned from account 'A'.

How can I prevent this from happening so that the data is only saved/returned for each particular user account? Should I be using something instead of localStorage like sessionStorage? Any help is appreciated.

I've solved this personally by including an identifier for the user in the local storage key. You'll have an entry per user and do the lookup based on the identifier. Something like:

localStorage.setItem(`watchlist:${user.id}`, data) // set

const watchlist = localStorage.getItem(`watchlist:${user.id}`) // get

As noted by @AlexB in the comments, be aware that multiple users on the same device will have the local data of any other users in their localStorage, so be sure to consider privacy.

Save your data with userId as key(unique for all user) and corresponding watchlist as data

localStorage.setItem('userId', data);

and then fetch it with the login user Id

localStorage.getItem('loginUserId');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM