Answer the question
In order to leave comments, you need to log in
How to work with arrays in localStorage?
Hello. Please tell me how to implement the following logic correctly:
I have the following structure:
class NavigateServise writes and reads data from localStorage.
navigateService.js
class NavigateServise {
constructor() {
this.list = [];
this.init();
}
init() {
console.log("init");
}
setData = (id) => {
this.list = this.list.includes(id) ? this.list.filter(n => n !== id) : [...this.list, id];
const listM = JSON.stringify(this.list);
window.localStorage.setItem('data', listM);
}
getData = () => {
return window.localStorage.getItem('data');
}
}
const navigateServise = new NavigateServise();
export {navigateServise};
const Item = (props) => {
console.log('Item render');
return (
<li
className="item"
onClick={props.clicked}
>
{props.item.value}
</li>
)
}
export default Item;
import React from "react";
import Item from "./Item";
import {navigateServise} from "./navigateServise";
class App extends React.Component {
constructor(props) {
super(props);
this.dataFromLocalStorage = JSON.parse(navigateServise.getData());
console.log(this.dataFromLocalStorage);
this.items = [
{id: 1, value: "item 1"},
{id: 2, value: "item 2"},
{id: 3, value: "item 3"},
{id: 4, value: "item 4"},
{id: 5, value: "item 5"},
{id: 6, value: "item 6"},
{id: 7, value: "item 7"},
{id: 8, value: "item 8"}
];
}
setData = (id) => {
navigateServise.setData(id);
};
render() {
return (
<React.Fragment>
{
this.items.map((item, index) => {
return (
<ul
className=""
key={index}
>
<Item
item={item}
clicked={() => this.setData(item.id)}
/>
</ul>
);
})
}
</React.Fragment>
);
}
}
export default App;
Answer the question
In order to leave comments, you need to log in
If I understand correctly, you need the data in LS to initialize the application. Create a function to work with local data, that is, change items in App, not NavigateServise (correct Servise to Service), and use the navigateServise.setData() method only to synchronize data in LS.
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question