Reputation: 1449
What is the best way to store data from let's say an AJAX call that I later on will use to present data? It is not always possible to use the data in the success
function. Is localStorage
considered a best practice?
localStorage.setItem("username", "John");
localStorage.getItem("username");
Ideally, I would use Angular or any other framework that handles this, but how should I do when I use vanilla JavaScript?
I know window.dataVariable
should be avoided.
Upvotes: 1
Views: 803
Reputation: 4830
The reason window.dataVariable
is discouraged is that it pollutes the global namespace with variables and could possibly be overridden elsewhere accidentally.
Storing it in localstorage would be a bad idea in my opinion as the serialization/deserialization would also need to be handled.
One simple way of handling this would be to create a custom namespace on the window object which will be the designated place to store data for future use.
Sample:
// Instantiate a namespace object before the AJAX runs
window._cache = {};
// Once AJAX call completes,
window._cache.dataVariable = data;
This will ensure your data is available for later without polluting the global namespace. (Although care must be taken to ensure the variables are added/modified only where it needs to be and in the correct order)
Upvotes: 1