Search code examples
javascriptnode.jsreactjsconventions

Can I use window.localStorage in my React application?


I have a React application that allows users to select their "Favorite" items from a master/detail view...

I want the user to be able to open up the website, select their "Favorites" without having to sign in, reload the page, and have their Favorites saved "on the website." I've tried using PHP cookies from another origin (read here: You can't set Cookies from a fetch request). I don't want to include another npm package (mostly because I just want to know what's really going on behind my dependencies), and the only solution I can come up with is to use

window.localStorage.setItem('key', 'value');

Am I right? Is there some other convention for this? What should I do?

Keep in mind: I'm running this on a Node.js server so I can't just set the cookies with a PHP request.


Solution

  • Just so it is stated in an answer

    React is a library to build ui components. Using local storage is not part of that objective, so you can use it, as is part of the specs in web (as well as sessionStorage. Anyway, you might want to separate the access of the localStorage in a separated file, that can be imported and tested - that means, a level of indirection