admin管理员组

文章数量:1295713

What's the best method of storing a users ID in ReactJS, so that all ponents 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 ponent (App), but page refreshes lose the id :(.

What's the best method of storing a users ID in ReactJS, so that all ponents 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 ponent (App), but page refreshes lose the id :(.

Share edited Feb 20, 2019 at 16:39 Mark 2,0711 gold badge16 silver badges26 bronze badges asked Feb 20, 2019 at 15:43 SE_1991SE_1991 6751 gold badge7 silver badges10 bronze badges 1
  • Well, when a page refreshes, you should probably download user ID again depending on your session? – Sulthan Commented Feb 20, 2019 at 16:15
Add a ment  | 

3 Answers 3

Reset to default 8

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/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/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!

本文标签: javascriptWhat39s the best solution for storing a users idStack Overflow