简体   繁体   中英

What's the best solution for storing a users id?

What's the best method of storing a users ID in ReactJS, so that all components have access to it?

I've looked into Redux and Context, but they seem massively overkill for just storing an ID (or maybe I'm missing something?). I've also looked at storing the ID in the parent component (App), but page refreshes lose the id :(.

Session storage would probably best suit your needs

The sessionStorage property allows you to access a session Storage object for the current origin. sessionStorage is similar to localStorage; the only difference is while data stored in localStorage has no expiration time, data stored in sessionStorage gets cleared when the page session ends.

https://developer.mozilla.org/en-US/docs/Web/API/Window/sessionStorage

You can then set/get the ID when you need to

sessionStorage.setItem('userID', 'value');
const USER_ID = sessionStorage.getItem('userID');

However, to keep the ID even after a page close you would need to use localStorage

The read-only localStorage property allows you to access a Storage object for the Document's origin; the stored data is saved across browser sessions. localStorage is similar to sessionStorage, except that while data stored in localStorage has no expiration time, data stored in sessionStorage gets cleared when the page session ends — that is, when the page is closed.

https://developer.mozilla.org/en-US/docs/Web/API/Window/localStorage

localStorage.setItem('userID', 'value');
const USER_ID = localStorage.getItem('userID');

If you want your data to be available even after closing and reopening the browser, LocalStorage is the appropriate place to store it; Otherwise SessionStorage keeps your data as long as the browser is open.

Keeping such sensitive data as a user id in storage is a bad bad idea! You need to fetch this data every time the user hard-refreshes his/her browser. Do not use storage for such savings!

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