3

I'm trying to store arrays in localStorage on the clients browser for easy access of the content after the page has loaded, the arrays are pulled from a database.

My problem is that I can only use the local storage once the page has reloaded and it has reflected on the client, similar to this problem HERE with cookies.

I can't seem to find a solution to this. Any help would be appreciated some code:

localStorage.setItem('owner', JSON.stringify(data));    
var seat = JSON.parse(localStorage.getItem('owner'));
Community
  • 1
  • 1
  • 1
    Not certain what issue is? Question title references `localStorage` though `sessionStorage` is used at `javascript` at Question body? – guest271314 Nov 03 '16 at 02:56
  • @guest271314 sorry, fixed it. Though the same applies with session storage, unless the page is refreshed. –  Nov 03 '16 at 02:58
  • Unless the page is reloaded you cannot perform the next portion of the process? Or, are you not able to get `localStorage` after setting? – guest271314 Nov 03 '16 at 02:59
  • locaStorage cannot be used unless the page is reloaded, no. I need to use it straight away, is there a work around for this, like there is for cookies? @guest271314 –  Nov 03 '16 at 03:05
  • You should be able to get `localStorage` following setting `localStorage`. You also have access to `data` before and after setting `data` at `localStorage`. What are you trying to achieve? – guest271314 Nov 03 '16 at 03:07
  • No, I'm unable to use localStorage until the page is refreshed. Data is a returned array from an ajax call to a php script for grabbing col entries. It gets overwritten. –  Nov 03 '16 at 03:11
  • Can you explain what your trying to do? You are caching a value *you already have*. Why do you need to get it from localStorage again if you have it as 'data' already? – Raymond Camden Nov 07 '16 at 03:59
  • Also, you didn't say how your code fails. When you look at 'seat', what's wrong with it? Remember you JSON encoded it when you set it, so you will need to JSON parse it too. – Raymond Camden Nov 07 '16 at 04:00
  • @RaymondCamden The values need to be displayed to the user when he/she hovers over a div. Without having to fetch the data each time from the database. –  Nov 13 '16 at 21:51
  • Ok, well see my earlier comment. Did you JSON parse the loaded value? How exactly did your code fail? – Raymond Camden Nov 14 '16 at 14:24

1 Answers1

-1

You could await for local storage to be set before accessing it

(async () => await localStorage.setItem('owner', JSON.stringify(data)))();    
var seat = JSON.parse(localStorage.getItem('owner'));
Swaleh Matongwa
  • 698
  • 9
  • 16