S
S
s243442019-02-12 16:35:14
JavaScript
s24344, 2019-02-12 16:35:14

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};

Item.js
const Item = (props) => {
  console.log('Item render');
  return (
    <li
      className="item"
      onClick={props.clicked}
    >
      {props.item.value}
    </li>
  )
}

export default Item;

app.js
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;

When there is no data in localStorage, I write it there. When I reload the page, at the moment and click on the elements, I overwrite the data again. I need to continue working with existing ones. I will be grateful for any help.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
M
mxmvshnvsk, 2019-02-12
@s24344

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 question

Ask a Question

731 491 924 answers to any question