I'm brand new to react, so bare with me.
I have some data set in local storage before i start my react application, and i want to dynamically loop through local storage and display the data.
Currently I have it explicitly set:
import React from 'react';
const App = () => {
return (
<div>
<h1>Hello World</h1>
<ul>
<li>locale: {localStorage.getItem('locale')}</li>
<li>pubKey: {localStorage.getItem('pubKey')}</li>
<li>version: {localStorage.getItem('version')}</li>
<li>dist: {localStorage.getItem('dist')}</li>
</ul>
</div>
);
}
export default App;
but i want to not do explicit definitions, but loop through the localstorage data this dynamically.
elegant and complex solutions always welcome as well.
UPDATE::
I've tried:
in html:
<script>
window.localStorage.setItem('app:data:persist',JSON.stringify({"version":"0.0.1","dist":"shard","locale":"en_US","pubKey":"6asd68d68ddd6saadd79asd7das79ads9"}));</script></head>
<body>
const App = () => {
const localStorageData = JSON.parse(window.localStorage.getItem('app:data:persist'));
return (
<div>
<h1>Hello World</h1>
<ul>
{localStorageData.map((data,key) => {
return (
<li>{key} : {data[key]}</li>
)
})};
</ul>
</div>
);
}
but i cant get the value for the entry with the key correctly?
It's not clear about handle this dynamically and explicit definitions. Please clarify. If you use Redux, you can use https://github.com/rt2zz/redux-persist. Load the cached data into the redux store from the store engine when the application initializes.
If you don't want to use redux, just use one cache key for the whole cached data of the application.
Also, consider using React context to hold the cached data, so that nested components can access the cached data conveniently.
E.g.
localStorage.setItem('myapp:1.0.0:persist', JSON.stringify({ list, ... }));
const data = JSON.parse(localStorage.getItem('myapp:1.0.0:persist'));
data.list.map(...)