2

I have been trying to get react grid layout setup with my project and have been unable to merge two of the examples. Local storage and add/remove widgets

I figured I needed to also store items in LS and have been trying to get it working but with no luck. Currently, items are being stored, and layout is empty (not sure why), but the items are reset on refresh. I'm pretty sure it's because of the .map in state, but I am unsure how I can fix this.

If anything can help me I would be grateful as I have been stuck on this for awhile.

I have made a sandbox for ease of help

Clue Less
  • 47
  • 8

1 Answers1

2

I think this has to do with the fact that the first render of the ResponsiveReactGridLayout component counts as an onChange call. Therefore, it will call saveToLS() with an empty array of items. You should include a useEffect which will get the layout stored in localStorage upon page load. Then store the retrieved layout in a useState and pass this to the ResponsiveReactGridLayout component. After that you could set a flag that allows the ResponsiveReactGridLayout to update and save the layout to local storage, but this is optional.

Also, I would highly recommend changing your code from class based to functional code. Class based coding in React is mostly outdated and only used in specific use cases. Functional programming would future proof your code.

Jeroen
  • 311
  • 2
  • 14
  • 1
    Thank you so much for your help. I will start looking into how to do this as I am quite new to react (If you have any helpful links i would be grateful). Also, thank you for the heads up about class-based code – Clue Less Aug 26 '22 at 12:51
  • 1
    @ClueLess Anytime – Jeroen Aug 26 '22 at 12:54
  • 3
    Adding onto @Jeroen's answer, the new React docs (https://beta.reactjs.org/learn) are a great way to get started. As Jeroen mentioned, here is a React hook implementation: https://codesandbox.io/s/boring-wave-oo1wdu?file=/src/DashboardSystem.js – Cheese Aug 26 '22 at 14:17
  • 1
    @ClueLess A good way to learn React is by using Udemy. Personally I followed [this course by Maximilian Schwarzmüller](https://www.udemy.com/course/react-the-complete-guide-incl-redux/). Thought me everything I needed to have a career in React development. You could also have a look at TypeScript if you're serious about a career in React development – Jeroen Aug 26 '22 at 14:26