'useState to set iterated data

I need to do some plotting, which requires the data to presented in a certain way, i.e.:

[{
    type: "box",
    y: data[1],
    name: "1",
    boxpoints: "all",
  },
  {
    type: "box",
    y: data[2],
    name: "2",
    boxpoints: "all",
  },
   {
    type: "box",
    y: data[3],
    name: "3",
    boxpoints: "all",
}]

My data is set somewhere else via the useState hook:

const [data, setData] = useState([])

And now I would like to set another useState, which contains the above, i.e. the manual way would be to just do:

const [plotData, setPlotData] = useState([])

setPlotData([{
    type: "box",
    y: data[1],
    name: "1",
    boxpoints: "all",
  },
  {
    type: "box",
    y: data[2],
    name: "2",
    boxpoints: "all",
  },
   {
    type: "box",
    y: data[3],
    name: "3",
    boxpoints: "all",
}])

And then everything works. The problem is that I don't know in advance the length of the data. So in this case I know it's 3, and can do it manually, but it could be another value. Therefore I would like to iterate through it, also to keep the code more clean.

But I am unsure how I actually create this iteration/list of dictionaries on a useState.



Solution 1:[1]

This sounds like a perfect use for the memo hook which can create a computed value based on state dependencies.

const plotData = useMemo(
  () =>
    data.slice(1).map((y, i) => ({
      y,
      name: (i + 1).toString(),
      type: "box",
      breakpoints: "all",
    })),
  [data]
);

The use of data.slice(1) is because you seemed to want to skip the first entry in data based on your examples.

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Phil