Search code examples
reactjsreact-hooksstatesyncfusion

How change React state if it is multidimensional array and contain objects?


I have a state.

This state source in a file: dummy.js

This state contain complex data structure, this name stackedCustomSeries.

stackedCustomSeries is an array and contain two objects.

Each objects have several property: dataSource, xName, yName ...etc

The dataSource property contain stackedChartData[0]

The stackedChartData[0] is also an array.

The stackedChartData[0] contain two array.

These array's contain several objects.

Inside these objects have several x and y property.

I want to change this x and y properties value when I was clicked.

For example I click and pass data: 120

and in stackedChartData[0] { x: 'Jan', y: 111.1 }, would be >> { x: 'Jan', y: 120 },

But How?

I import my datasource in a state in my App component

App.js

import React, { useState } from "react";
import {
  stackedCustomSeries, 
} from "../../data/dummy";

  const App = () => {
    const [customSeries, setCustomSeries] = useState(stackedCustomSeries);
  
    const handleClick = () => {
    //What write here ?
    };  
   
    return (          
        <div className="m-5">
          <button type="button" onClick={handleClick}>
            ChangeButton
          </button>         
        </div>
   
    );
  };
  
  export default App;

dummy.js

export const stackedChartData = [
  [
    { x: 'Jan', y: 111.1 },
    { x: 'Feb', y: 127.3 },
    { x: 'Mar', y: 143.4 },
    { x: 'Apr', y: 159.9 },
    { x: 'May', y: 159.9 },
    { x: 'Jun', y: 159.9 },
    { x: 'July', y: 159.9 },
  ],
  [
    { x: 'Jan', y: 111.1 },
    { x: 'Feb', y: 127.3 },
    { x: 'Mar', y: 143.4 },
    { x: 'Apr', y: 159.9 },
    { x: 'May', y: 159.9 },
    { x: 'Jun', y: 159.9 },
    { x: 'July', y: 159.9 },
  ],
];

export const stackedCustomSeries = [

  { dataSource: stackedChartData[0],
    xName: 'x',
    yName: 'y',
    name: 'Budget',
    type: 'StackingColumn',
    background: 'blue',

  },

  { dataSource: stackedChartData[1],
    xName: 'x',
    yName: 'y',
    name: 'Expense',
    type: 'StackingColumn',
    background: 'red',

  },

];


Solution

  •   const handleClick = (value) => {
        const copiedCustomerSeries = [...customSeries];
        const updatedCustomerSeries = copiedCustomerSeries.map((cs, index) => {
          if (index === 0) {
            const updatedSingleCustomerSeries = {
              ...cs,
              dataSource: [...cs.dataSource].map((ds) =>
                ds.x === "Jan" ? { ...ds, y: value } : ds
              )
            };
            return updatedSingleCustomerSeries;
          } else return cs;
        });
        console.log(updatedCustomerSeries);
        setCustomSeries(updatedCustomerSeries)
      };