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
3 Answers
Reset to default 8Session 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
版权声明:本文标题:javascript - What's the best solution for storing a users id? - Stack Overflow 内容由网友自发贡献,该文观点仅代表作者本人, 转载请联系作者并注明出处:http://www.betaflare.com/web/1741623031a2388919.html, 本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容,一经查实,本站将立刻删除。
发表评论