Skip to content

Combining add/remove with saving grid layout to LS #1406

@lallen-6

Description

@lallen-6

I am trying to implement the react-grid-layout where I can add/remove grid items and also save the layout to local storage using an individual username as a key. I have tried to implement this but am getting errors which ever way I try it, below is my code for the react grid, could someone advise where I am going wrong...

const ReactGridLayout = WidthProvider(Responsive);

//Find username form localstorage (uuid string)
const username = localStorage.getItem('username')

const Dash = (props) => {
  //Variable used for id of grid component:
  const id = uuid()

  //Hook to set layout state
  const originialLayouts = getLayout("layouts") || {}
  const savedLayout = JSON.parse(JSON.stringify(originialLayouts))
  

  //column size is static
  //layouts taken from local storage via function
  const [ state, setState ] = React.useState({
    cols: { lg: 12, md: 10, sm: 6, xs: 4, xxs: 2 },
    rowHeight: 30,
    layouts: {},
    layout: [].map(function(i, list) {
      return {
        i: i.toString(),
        x: i * 2,
        y: 0,
        w: 3,
        h: 3,
        add: i === (list.length - 1)
      }
    })
  })

  //function ammends layout array with additional grid item
  const addItem = (item) => { 
    console.log('adding: ' + id);
    const newLayout = state.layout;
    newLayout.push({
      i: `${id}`,
      x: (state.layout.length * 3) % (state.cols || 12),
      y: 0,
      w: 3,
      h: 3
    })
    setState({layout: newLayout})
  }

  //function to remove grid item on click
  const removeItem = (i) => {
    console.log(i)
    setState({ layout: _.reject(state.layout, { i:i }) })     
  }

  // function to calculate where to add items based on the cols
  const onBreakpointChange = (breakpoint, cols) => {
    setState({
      cols: cols,
      breakpoint: breakpoint
    })
    console.log(state)
  }

  //function to save layout to LS everytime a grid item is moved.
  const onLayoutChange = (layout, layouts) => {
    saveLayout("layouts", layouts)
    setState({ layout: layout})
  }


  return (
    <div>
      <button onClick={addItem}>Add Item</button>
        <ReactGridLayout
          className="layout"
          layouts={state.layouts}
          breakpoints={{ lg: 1200, md: 996, sm: 768, xs: 480, xxs: 0 }}
          onLayoutChange={(layout, state) => onLayoutChange(layout, state)}
          onBreakpointChange={onBreakpointChange}
          cols={{ lg: 12, md: 12, sm: 6, xs: 4, xxs: 2 }}
          resizeHandles={['s', 'w', 'e', 'n', 'sw', 'nw','se', 'ne']}
          compactType={"vertical"}
          draggableHandle=".dragHandle"               
      >        
        {_.map(state.layout, (item, i) => (
          <div key={item.i} data-grid={state.layout[i]}>            
            <div className='dragHandle'>Drag From Here</div>                        
            <DashItem>
            <button onClick={() => removeItem(item.i)}>Remove Item</button>  
                 <CreateGraph data={state.layout[i]}/>
            </DashItem>
            <div className='dragHandle'>Drag From Here</div>
          </div>
        ))}
        </ReactGridLayout>
    </div>
  );
}

//function to get user layout from LS
const getLayout = (key) => {
  let ls = {};
  if (global.localStorage) {
    try {
      ls = JSON.parse(global.localStorage.getItem(username)) || {};
    } catch (error) {
      console.log('error with getLayout')
    }
  }
  return ls[key]
}

//function to save user layout to LS
const saveLayout = ( key, value ) => {
  if (global.localStorage) {
    global.localStorage.setItem( username, JSON.stringify({ [key]: value}) );
  }
}

export default Dash;

Metadata

Metadata

Assignees

No one assigned

    Labels

    questionstaleThe label to apply when a pull request or an issue is stale

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions