Change Status Bar Component when data change in React AgGrid - javascript

I need to change the value I show in my custom status bar when a prop changes.
So let's say I got:
const CustomGrid = ({
data, lastUpdate, framweworkComponents, columns
}) => {
const [gridApi, setGridApi] = useState(null);
const [gridColumnApi, setGridColumnApi] = useState(null);
const [gridParams, setGridParams] = useState(null);
const onGridReady = (params) => {
setGridApi(params.api);
setGridColumnApi(params.columnApi);
setGridParams(params);
}
};
const renderLastUpdateStatusBar = () => (
<div>
{lastUpdate}
</div>
);
return(
<div className={theme || 'ag-theme-balham'} style={style}>
<AgGridReact
modules={AllModules}
onGridReady={onGridReady}
columnDefs={columns}
rowData={data}
defaultColDef={defaultColDef || {
resizable: true,
menuTabs: [],
}}
frameworkComponents={{
...frameworkComponents,
lastUpdateStatusBarComponent: renderLastUpdateStatusBar,
}}
statusBar={{
statusPanels: [
{
statusPanel: 'lastUpdateStatusBarComponent',
key: 'lastUpdateStatusBarKey',
align: 'left',
},
],
}
/>
</div>
)
}
When 'lastUpdate' changes, it is correctly passed to CustomGrid component but the status bar doesn't get re-rendered, so I see the first value forever.
My goal is to make the status bar updating every time 'lastUpdate' changes. I tried making a state containing my framework components and set it in a useEffect when lastUpdate changes, then put this state in frameworkComponents prop in agGrid, but it does not work:
const [frameworkC, setFrameworkC] = useState(null);
useEffect(() => {
setFrameworkC({
...frameworkComponents,
lastUpdateStatusBarComponent: renderLastUpdateStatusBar,
})
}, [lastUpdate]);
...
<AgGridReact
...
frameworkComponents={frameworkC}
...
>
I also tried setting this state in onGridReady function, same result.
Also I tried calling api.redrawRows(gridParams) in the useState, no way.
Is there some API I can use to update the status bar component? Or some any approach?

You need to add key for the component to rerender
<AgGridReact
key={lastUpdate}
modules={AllModules}
onGridReady={onGridReady}
columnDefs={columns}
rowData={data}
defaultColDef={defaultColDef || {
resizable: true,
menuTabs: [],
}}
frameworkComponents={{
...frameworkComponents,
lastUpdateStatusBarComponent: renderLastUpdateStatusBar,
}}
statusBar={{
statusPanels: [
{
statusPanel: 'lastUpdateStatusBarComponent',
key: 'lastUpdateStatusBarKey',
align: 'left',
},
],
}
/>

Related

This filter method is working in console but not in ui in react

I want to filter items by filter method and I did it but it doesn't work in UI but
when I log it inside console it's working properly
I don't know where is the problem I put 2 images
Explanation of this code:
Looping inside currencies_info by map method and show them when I click on it and this completely working then I want filter the list when user enter input inside it I use filter method and this completely working in console not in UI
import React, { useState } from "react";
// Artificial object about currencies information
let currencies_info = [
{
id: 1,
name: "بیت کوین (bitcoin)",
icon: "images/crypto-logos/bitcoin.png",
world_price: 39309.13,
website_price: "3000",
balance: 0,
in_tomans: 0
},
{
id: 2,
name: "اتریوم (ethereum)",
icon: "images/crypto-logos/ethereum.png",
world_price: 39309.13,
website_price: "90",
balance: 0,
in_tomans: 0
},
{
id: 3,
name: "تتر (tether)",
icon: "images/crypto-logos/tether.png",
world_price: 39309.13,
website_price: "5",
balance: 0,
in_tomans: 0
},
{
id: 4,
name: "دوج کوین (dogecoin)",
icon: "images/crypto-logos/dogecoin.png",
world_price: 39309.13,
website_price: "1000000",
balance: 0,
in_tomans: 0
},
{
id: 5,
name: "ریپل (ripple)",
icon: "images/crypto-logos/xrp.png",
world_price: 39309.13,
website_price: "1,108",
balance: 0,
in_tomans: 0
}
];
export default function Buy() {
// States
let [api_data, set_api_data] = useState(currencies_info);
const [currency_icon, set_currency_icon] = useState("");
const [currency_name, set_currency_name] = useState("");
const [currency_price, set_currency_price] = useState(0);
const [dropdown, set_drop_down] = useState(false);
let [search_filter, set_search_filter] = useState("");
// States functions
// this function just toggle dropdown list
const toggle_dropdown = () => {
dropdown ? set_drop_down(false) : set_drop_down(true);
};
// this function shows all currencies inside dropdown list and when click on each item replace
// the currency info and hide dropdown list
const fetch_currency = (e) => {
set_drop_down(false);
currencies_info.map((currency) => {
if (e.target.id == currency.id) {
set_currency_name(currency.name);
set_currency_icon(currency.icon);
set_currency_price(currency.website_price);
}
});
};
// this function filter items base on user input value
const filter_currency = (e) => {
set_search_filter = currencies_info.filter((currency) => {
return currency.name.indexOf(e.target.value) !== -1;
});
api_data = set_search_filter;
console.log(api_data);
};
return (
<div className="buy-page-input" onClick={toggle_dropdown}>
{/* currency logo */}
<div className="currency-logo">
<img src={currency_icon} width="30px" />
</div>
{/* currency name in persian */}
<span className="currency-name">{currency_name}</span>
{/* currency dropdown icon */}
<div className="currency-dropdown">
<img className={dropdown ? "toggle-drop-down-icon" : ""}
src="https://img.icons8.com/ios-glyphs/30/000000/chevron-up.png"
/>
</div>
</div>
{/* Drop down list */}
{dropdown ? (
<div className="drop-down-list-container">
{/* Search box */}
<div className="search-box-container">
<input type="search" name="search-bar" id="search-bar"
placeholder="جستجو بر اساس اسم..."
onChange={(e) => {
filter_currency(e);
}}/>
</div>
{api_data.map((currency) => {
return (<div className="drop-down-list" onClick={(e) => {
fetch_currency(e);}} id={currency.id}>
<div class="right-side" id={currency.id}>
<img src={currency.icon} width="20px" id={currency.id} />
<span id={currency.id}>{currency.name}</span>
</div>
<div className="left-side" id={currency.id}>
<span id={currency.id}>قیمت خرید</span>
<span className="buy-price" id={currency.id}>
{currency.website_price}تومان</span>
</div>
</div>);})}
</div>) : ("")});}
Your search_filter looks redundant to me.
Try to change the filter_currency function like this:
const filter_currency = (e) => {
const search = e.target.value;
const filtered = currencies_info.filter((currency) => {
return currency.name.includes(search);
});
set_api_data(filtered);
};
It looks like you are never setting the api_data after you set the filter state.
Change the following
api_data = set_search_filter
console.log(api_data)
to
api_data = set_search_filter
set_api_data(api_data)
However, it then looks like set_search_filter is never used and only set so to improve this further you could remove that state and just have it set the api_data direct. Something like this:
const filter_currency = (e) => {
const search_filter = currencies_info.filter((currency) => {
return currency.name.indexOf(e.target.value) !== -1
})
set_api_data(search_filter)
}
Change your state value from string to array of the search_filter like this -
let [search_filter, set_search_filter] = useState([]);
and also it should be like this -
const filter_currency = (e) => {
const filterValues = currencies_info.filter((currency) => {
return currency.name.indexOf(e.target.value) !== -1;
});
set_search_filter(filtervalues);
set_api_data(filterValues);
console.log(filterValues);
};
and use useEffect with search_filter as dependency, so that every time search_filter value is being set, useEffect will trigger re render, for eg:-
useEffect(()=>{
//every time search_filter value will change it will update the dom.
},[search_filter])

AG Grid React: How to get the state of rows after changing the order?

After implementing the drag and drop feature on AG Grid table, I'm looking for a way to get the current state with the updated order/index of rows. My goal is to persist the table data after changing the order, but can't find the respective state of the current order.
I'd appreciate any help or any idea.
Sandbox demo and example code below
import React from "react";
import { AgGridReact } from "ag-grid-react";
import "ag-grid-community/dist/styles/ag-grid.css";
import "ag-grid-community/dist/styles/ag-theme-alpine.css";
function App() {
const [gridApi, setGridApi] = React.useState(null);
const [gridColumnApi, setGridColumnApi] = React.useState(null);
const onGridReady = (params) => {
setGridApi(params.api);
setGridColumnApi(params.columnApi);
};
const defaultColDef = {
flex: 1,
editable: true
};
const columnDefs = [
{
headerName: "Name",
field: "name",
rowDrag: true
},
{ headerName: "stop", field: "stop" },
{
headerName: "duration",
field: "duration"
}
];
const rowData = React.useMemo(
() => [
{
name: "John",
stop: 10,
duration: 5
},
{
name: "David",
stop: 15,
duration: 8
},
{
name: "Dan",
stop: 20,
duration: 6
}
],
[]
);
return (
<div>
<h1 align="center">React-App</h1>
<div>
<div className="ag-theme-alpine" style={{ height: "700px" }}>
<AgGridReact
columnDefs={columnDefs}
rowData={rowData}
defaultColDef={defaultColDef}
onGridReady={onGridReady}
rowDragManaged={true}
></AgGridReact>
</div>
</div>
</div>
);
}
export default App;
You can get the order of the rows inside the grid by iterating over them using the Grid API method forEachNode:
API for Row Nodes
const rows = [];
gridApi.forEachNodeAfterFilterAndSort((node) => rows.push(node.data));
console.log(rows);
See this implemented in the following sample.
You're currently using managed dragging by passing rowManagedDragging={true}, which means the AgGridReact component is managing the row order state.
If you want to maintain row order state outside the component, you need to use Unmanaged Dragging.
Add a handler for onRowDragMove, and use the node and overIndex or overNode properties of the event to update your local event order state, and pass it to the AgGridReact component to re-render.
Take a look at this example from the docs

How do I sustain data from DB while using another GET request with different query string in React(Next.js)?

I don't speak English very well. Please be understanding!
First, please check my code!
export default function DriveFolder() {
const [clickFolderPk, setClickFolderPk] = useState(1);
const viewFolder = async () => {
const url = `/api/store/drive/view-folder?folderId=${clickFolderPk}`;
await get(url)
.then((res) => {
console.log(res);
setMainFolder(res.directChildrenFolders);
})
.catch((error) => {
console.log(error);
});
};
useEffect(() => {
viewFolder();
}, [clickFolderPk]);
return (
<div className={classes.driveFolder}>
{mainFolder.map((main, key) => (
<TreeView>
<TreeItem
onClick={() => setClickFolderPk(main.FOLDER_PK)}>
<TreeItem nodeId='10' label='OSS' />
<TreeItem nodeId='6' label='Material-UI'>
<TreeItem nodeId='7' label='src'>
<TreeItem nodeId='8' label='index.js' />
<TreeItem nodeId='9' label='tree-view.js' />
</TreeItem>
</TreeItem>
</TreeItem>
</TreeView>
))}
</div>
);
}
I edited some code to make it clear. (might misspelled)
With this code, on the first rendering, since 'clickFolderPk' value is 1, I get the right data from DB.
However, since I have subfolders within folders from 'clickFolderPk' value 1, I have to request another GET REQUEST to see my subfolders from root folders.
Here is the simple image that you can understand my situation better.
this is what I get from 'clickFolderPk' value 1.
However, when I press 'kikiki', GET request functions and render like this.
.
This is not the way I want to render things.
I want every data from DB, however they don't disappear whenever I use different GET request with different PK number.
I want them stay on the screen and get the subfolders within them.
I'm struggling with this issue for quite a time.
Your help will be really appreciated!!!!!
It's all about Nesting: Folders have sub-folders, etc and it goes on...
Note: To break things down, I will answer from a React point of view disregarding how your backend api is structured or returns data.
Basically there are two main approaches,
Approach #1:
The global state is a single source of truth for all the folders think of it like this:
const [allFolders, setAllFolders] = useState([
{
id: "1",
name: "a-1",
folders: [
{
name: "a-subfolder-1",
folders: [{ name: "a-subfolder-subfolder-1" }],
},
{ name: "subfolder-2" },
],
},
]);
The problem is that any small update requires to mutate the entire state. So I will focus more on Approach #2
Approach #2:
There is the main tree that has child components, child components can expand and have children too:
import { useEffect, useState } from "react";
import "./styles.css";
export default function DriveFolder() {
const [folders, setFolders] = useState([
{ id: "1", name: "folder-a" },
{ id: "2", name: "folder-b" },
{ id: "3", name: "folder-c" }
]);
return (
<div style={{ display: "flex", flexDirection: "column" }}>
{folders.map((folder) => {
return <Folder key={folder.id} folder={folder} />;
})}
</div>
);
}
const Folder = ({ parent = undefined, folder }) => {
const [subfolders, setSubfolders] = useState([]);
const [isOpened, setOpened] = useState(false);
const hasSubfolders = subfolders.length > 0;
useEffect(() => {
// send request to your backend to fetch sub-folders
// --------------- to ease stuff I will hard code it
// with this you can limit the example of nest you wish
const maxNestsCount = 5;
const subfolderParent = parent || folder;
const subfolder = {
id: subfolderParent.id + "-sub",
name: "subfolder-of-" + subfolderParent.name
};
const currentNestCount = subfolder.name.split("-sub").length;
setSubfolders(currentNestCount < maxNestsCount ? [subfolder] : []);
// -----------------------------
}, []);
const handleToggleShowSubFolders = (e) => {
e.stopPropagation();
if (!hasSubfolders) {
return;
}
setOpened(!isOpened);
};
return (
<div
style={{
display: "flex",
flexDirection: "column",
paddingHorizontal: 5,
marginTop: 10,
marginLeft: parent ? 20 : 0,
backgroundColor: "#1678F230",
cursor: hasSubfolders ? "pointer" : undefined
}}
onClick={handleToggleShowSubFolders}
>
{folder.name}
<div style={{ display: isOpened ? "block" : "none" }}>
{subfolders.map((subfolder) => (
<Folder key={subfolder.id} parent={folder} folder={subfolder} />
))}
</div>
</div>
);
};
Try it out:
Here is the output of the sample code above:

React - How can I parse large JSON objects for graphing. Struggling to do so with State

I'm having trouble parsing large JSON objects from my Axios calls and setting them as a state to then be passed as X and Y axis data for graphing in react-chartist. For my case, I'm charting stock market data.
I have been trying to parse the data using state hooks, chartData, but can't get it working, like so response.data.symbol, response.data.adj_close, and response.data.date
I also tried creating three different states, for X, Y, and symbol data taken directly from the axios call, but wasn't able to accomplish so.
Here is the code I'm using:
export default function Graph() {
const [chartData, setChartData] = useState([])
const getData = () => {
axiosInstance
.get('price/' + slug)
.then(result => setChartData(result.data))
}
useEffect(() => {
getData()
}, [])
const graphChart = () =>
{
var data = {
labels: //date values from JSON object
series: //adj_close values from JSON object
};
var options = {
width: 500,
height: 400
};
return (
<ChartistGraph data={data} options={options} type="Line" />
);
};
return (
<Container>
<Grid>
{graphChart()}
</Grid>
</Container>
);
};
Am I approaching this wrong? Is there a simpler way to do so?
I've added the data to replicate the problem, which basically is, how can I parse large objects like this? Keeping in mind that each row needs to be grouped by it's respective symbol for graphing. In the data below, there are 8 companies worth of data. Putting all of this data on a graph would be bad, but if I knew how to parse specific symbols, then I will be able to accomplish graphing on my own.
[{"symbol":"PG","date":"2020-12-04","adj_close":137.47},
{"symbol":"HSY","date":"2020-12-04","adj_close":150.87},
{"symbol":"CLX","date":"2020-12-04","adj_close":199.98},
{"symbol":"COST","date":"2020-12-04","adj_close":373.43},
{"symbol":"MDLZ","date":"2020-12-04","adj_close":59.03},
{"symbol":"K","date":"2020-12-04","adj_close":62.37},
{"symbol":"KHC","date":"2020-12-04","adj_close":34.12},
{"symbol":"PEP","date":"2020-12-04","adj_close":145.85},
{"symbol":"PG","date":"2020-12-07","adj_close":137.68},
{"symbol":"HSY","date":"2020-12-07","adj_close":149.72},
{"symbol":"CLX","date":"2020-12-07","adj_close":200.61},
{"symbol":"COST","date":"2020-12-07","adj_close":373.33},
{"symbol":"MDLZ","date":"2020-12-07","adj_close":58.41},
{"symbol":"K","date":"2020-12-07","adj_close":61.95},
{"symbol":"KHC","date":"2020-12-07","adj_close":33.6},
{"symbol":"PEP","date":"2020-12-07","adj_close":145.37},
{"symbol":"PG","date":"2020-12-08","adj_close":138.05},
{"symbol":"HSY","date":"2020-12-08","adj_close":150.63},
{"symbol":"CLX","date":"2020-12-08","adj_close":202.88},
{"symbol":"COST","date":"2020-12-08","adj_close":377.6},
{"symbol":"MDLZ","date":"2020-12-08","adj_close":58.29},
{"symbol":"K","date":"2020-12-08","adj_close":62.55},
{"symbol":"KHC","date":"2020-12-08","adj_close":34.34},
{"symbol":"PEP","date":"2020-12-08","adj_close":145.52},
{"symbol":"PG","date":"2020-12-09","adj_close":136.41},
{"symbol":"HSY","date":"2020-12-09","adj_close":152.14},
{"symbol":"CLX","date":"2020-12-09","adj_close":200.51},
{"symbol":"COST","date":"2020-12-09","adj_close":374.29},
{"symbol":"MDLZ","date":"2020-12-09","adj_close":57.72},
{"symbol":"K","date":"2020-12-09","adj_close":62},
{"symbol":"KHC","date":"2020-12-09","adj_close":34.22},
{"symbol":"PEP","date":"2020-12-09","adj_close":145.69},
{"symbol":"PG","date":"2020-12-10","adj_close":135.51},
{"symbol":"HSY","date":"2020-12-10","adj_close":149.7},
{"symbol":"CLX","date":"2020-12-10","adj_close":200.6},
{"symbol":"COST","date":"2020-12-10","adj_close":372.79},
{"symbol":"MDLZ","date":"2020-12-10","adj_close":57.18},
{"symbol":"K","date":"2020-12-10","adj_close":61.98},
{"symbol":"KHC","date":"2020-12-10","adj_close":34.1},
{"symbol":"PEP","date":"2020-12-10","adj_close":144.67},
{"symbol":"PG","date":"2020-12-11","adj_close":136.51},
{"symbol":"HSY","date":"2020-12-11","adj_close":149.11},
{"symbol":"CLX","date":"2020-12-11","adj_close":201.73},
{"symbol":"COST","date":"2020-12-11","adj_close":375.1},
{"symbol":"MDLZ","date":"2020-12-11","adj_close":57.4},
{"symbol":"K","date":"2020-12-11","adj_close":62.11},
{"symbol":"KHC","date":"2020-12-11","adj_close":34.07},
{"symbol":"PEP","date":"2020-12-11","adj_close":144.97},
{"symbol":"PG","date":"2020-12-14","adj_close":135.85},
{"symbol":"HSY","date":"2020-12-14","adj_close":149.14},
{"symbol":"CLX","date":"2020-12-14","adj_close":202.38},
{"symbol":"COST","date":"2020-12-14","adj_close":374.38},
{"symbol":"MDLZ","date":"2020-12-14","adj_close":57.29},
{"symbol":"K","date":"2020-12-14","adj_close":61.92},
{"symbol":"KHC","date":"2020-12-14","adj_close":34.42},
{"symbol":"PEP","date":"2020-12-14","adj_close":144.23},
{"symbol":"PG","date":"2020-12-15","adj_close":136.65},
{"symbol":"HSY","date":"2020-12-15","adj_close":150.23},
{"symbol":"CLX","date":"2020-12-15","adj_close":203.04},
{"symbol":"COST","date":"2020-12-15","adj_close":371.88},
{"symbol":"MDLZ","date":"2020-12-15","adj_close":57.45},
{"symbol":"K","date":"2020-12-15","adj_close":61.24},
{"symbol":"KHC","date":"2020-12-15","adj_close":34.33},
{"symbol":"PEP","date":"2020-12-15","adj_close":144.77},
{"symbol":"PG","date":"2020-12-16","adj_close":137.27},
{"symbol":"HSY","date":"2020-12-16","adj_close":150.28},
{"symbol":"CLX","date":"2020-12-16","adj_close":203.44},
{"symbol":"COST","date":"2020-12-16","adj_close":369.44},
{"symbol":"MDLZ","date":"2020-12-16","adj_close":57.2},
{"symbol":"K","date":"2020-12-16","adj_close":61.5},
{"symbol":"KHC","date":"2020-12-16","adj_close":34.43},
{"symbol":"PEP","date":"2020-12-16","adj_close":144.89},
{"symbol":"PG","date":"2020-12-17","adj_close":138.25},
{"symbol":"HSY","date":"2020-12-17","adj_close":151.61},
{"symbol":"CLX","date":"2020-12-17","adj_close":202.34},
{"symbol":"COST","date":"2020-12-17","adj_close":370.29},
{"symbol":"MDLZ","date":"2020-12-17","adj_close":57.93},
{"symbol":"K","date":"2020-12-17","adj_close":62.48},
{"symbol":"KHC","date":"2020-12-17","adj_close":34.62},
{"symbol":"PEP","date":"2020-12-17","adj_close":145.71},
{"symbol":"PG","date":"2020-12-18","adj_close":139.04},
{"symbol":"HSY","date":"2020-12-18","adj_close":150.88},
{"symbol":"CLX","date":"2020-12-18","adj_close":203.17},
{"symbol":"COST","date":"2020-12-18","adj_close":367},
{"symbol":"MDLZ","date":"2020-12-18","adj_close":58.32},
{"symbol":"K","date":"2020-12-18","adj_close":62.08},
{"symbol":"KHC","date":"2020-12-18","adj_close":34.77},
{"symbol":"PEP","date":"2020-12-18","adj_close":146.93},
{"symbol":"PG","date":"2020-12-21","adj_close":137.52},
{"symbol":"HSY","date":"2020-12-21","adj_close":149.66},
{"symbol":"CLX","date":"2020-12-21","adj_close":202.45},
{"symbol":"COST","date":"2020-12-21","adj_close":364.97},
{"symbol":"MDLZ","date":"2020-12-21","adj_close":57.68},
{"symbol":"K","date":"2020-12-21","adj_close":61.53},
{"symbol":"KHC","date":"2020-12-21","adj_close":34.57},
{"symbol":"PEP","date":"2020-12-21","adj_close":145.4},
{"symbol":"PG","date":"2020-12-22","adj_close":136.55},
{"symbol":"HSY","date":"2020-12-22","adj_close":148.62},
{"symbol":"CLX","date":"2020-12-22","adj_close":201.39},
{"symbol":"COST","date":"2020-12-22","adj_close":362.03},
{"symbol":"MDLZ","date":"2020-12-22","adj_close":57.16},
{"symbol":"K","date":"2020-12-22","adj_close":61.19},
{"symbol":"KHC","date":"2020-12-22","adj_close":34.39},
{"symbol":"PEP","date":"2020-12-22","adj_close":144.02},
{"symbol":"PG","date":"2020-12-23","adj_close":136.34},
{"symbol":"HSY","date":"2020-12-23","adj_close":149.45},
{"symbol":"CLX","date":"2020-12-23","adj_close":202.33},
{"symbol":"COST","date":"2020-12-23","adj_close":361.89},
{"symbol":"MDLZ","date":"2020-12-23","adj_close":57.35},
{"symbol":"K","date":"2020-12-23","adj_close":61.61},
{"symbol":"KHC","date":"2020-12-23","adj_close":34.8},
{"symbol":"PEP","date":"2020-12-23","adj_close":144.41},
{"symbol":"PG","date":"2020-12-24","adj_close":137.72},
{"symbol":"HSY","date":"2020-12-24","adj_close":149.95},
{"symbol":"CLX","date":"2020-12-24","adj_close":203.8},
{"symbol":"COST","date":"2020-12-24","adj_close":364.58},
{"symbol":"MDLZ","date":"2020-12-24","adj_close":57.85},
{"symbol":"K","date":"2020-12-24","adj_close":61.78},
{"symbol":"KHC","date":"2020-12-24","adj_close":34.98},
{"symbol":"PEP","date":"2020-12-24","adj_close":145.06},
{"symbol":"PG","date":"2020-12-28","adj_close":138.68},
{"symbol":"HSY","date":"2020-12-28","adj_close":151.8},
{"symbol":"CLX","date":"2020-12-28","adj_close":202.25},
{"symbol":"COST","date":"2020-12-28","adj_close":371.06},
{"symbol":"MDLZ","date":"2020-12-28","adj_close":58.27},
{"symbol":"K","date":"2020-12-28","adj_close":62.34},
{"symbol":"KHC","date":"2020-12-28","adj_close":35.21},
{"symbol":"PEP","date":"2020-12-28","adj_close":146.91},
{"symbol":"PG","date":"2020-12-29","adj_close":138.42},
{"symbol":"HSY","date":"2020-12-29","adj_close":151.44},
{"symbol":"CLX","date":"2020-12-29","adj_close":201.76},
{"symbol":"COST","date":"2020-12-29","adj_close":372.72},
{"symbol":"MDLZ","date":"2020-12-29","adj_close":58.45},
{"symbol":"K","date":"2020-12-29","adj_close":62.29},
{"symbol":"KHC","date":"2020-12-29","adj_close":34.9},
{"symbol":"PEP","date":"2020-12-29","adj_close":147.42},
{"symbol":"PG","date":"2020-12-30","adj_close":137.77},
{"symbol":"HSY","date":"2020-12-30","adj_close":150.53},
{"symbol":"CLX","date":"2020-12-30","adj_close":201.04},
{"symbol":"COST","date":"2020-12-30","adj_close":374.45},
{"symbol":"MDLZ","date":"2020-12-30","adj_close":58},
{"symbol":"K","date":"2020-12-30","adj_close":61.53},
{"symbol":"KHC","date":"2020-12-30","adj_close":34.67},
{"symbol":"PEP","date":"2020-12-30","adj_close":147.31},
{"symbol":"PG","date":"2020-12-31","adj_close":139.14},
{"symbol":"HSY","date":"2020-12-31","adj_close":152.33},
{"symbol":"CLX","date":"2020-12-31","adj_close":201.92},
{"symbol":"COST","date":"2020-12-31","adj_close":376.78},
{"symbol":"MDLZ","date":"2020-12-31","adj_close":58.47},
{"symbol":"K","date":"2020-12-31","adj_close":62.23},
{"symbol":"KHC","date":"2020-12-31","adj_close":34.66},
{"symbol":"PEP","date":"2020-12-31","adj_close":148.3},
{"symbol":"PG","date":"2021-01-04","adj_close":137.82},
{"symbol":"HSY","date":"2021-01-04","adj_close":150.9},
{"symbol":"CLX","date":"2021-01-04","adj_close":200.44},
{"symbol":"COST","date":"2021-01-04","adj_close":380.15},
{"symbol":"MDLZ","date":"2021-01-04","adj_close":57.92},
{"symbol":"K","date":"2021-01-04","adj_close":61.45},
{"symbol":"KHC","date":"2021-01-04","adj_close":34.23},
{"symbol":"PEP","date":"2021-01-04","adj_close":144.27},
{"symbol":"PG","date":"2021-01-05","adj_close":138.7},
{"symbol":"HSY","date":"2021-01-05","adj_close":150.73},
{"symbol":"CLX","date":"2021-01-05","adj_close":200.01},
{"symbol":"COST","date":"2021-01-05","adj_close":375.74},
{"symbol":"MDLZ","date":"2021-01-05","adj_close":57.98},
{"symbol":"K","date":"2021-01-05","adj_close":61.8},
{"symbol":"KHC","date":"2021-01-05","adj_close":33.57},
{"symbol":"PEP","date":"2021-01-05","adj_close":144.7},
{"symbol":"PG","date":"2021-01-06","adj_close":140.16},
{"symbol":"HSY","date":"2021-01-06","adj_close":151.26},
{"symbol":"CLX","date":"2021-01-06","adj_close":197.41},
{"symbol":"COST","date":"2021-01-06","adj_close":370.02},
{"symbol":"MDLZ","date":"2021-01-06","adj_close":57.87},
{"symbol":"K","date":"2021-01-06","adj_close":61.32},
{"symbol":"KHC","date":"2021-01-06","adj_close":33.94},
{"symbol":"PEP","date":"2021-01-06","adj_close":142.93},
{"symbol":"PG","date":"2021-01-07","adj_close":138.85},
{"symbol":"HSY","date":"2021-01-07","adj_close":151.17},
{"symbol":"CLX","date":"2021-01-07","adj_close":196.43},
{"symbol":"COST","date":"2021-01-07","adj_close":367.92},
{"symbol":"MDLZ","date":"2021-01-07","adj_close":57.76},
{"symbol":"K","date":"2021-01-07","adj_close":60.89},
{"symbol":"KHC","date":"2021-01-07","adj_close":33.695},
{"symbol":"PEP","date":"2021-01-07","adj_close":142.47},
{"symbol":"PG","date":"2021-01-08","adj_close":138.79},
{"symbol":"HSY","date":"2021-01-08","adj_close":152.03},
{"symbol":"CLX","date":"2021-01-08","adj_close":197.84},
{"symbol":"COST","date":"2021-01-08","adj_close":369.94},
{"symbol":"MDLZ","date":"2021-01-08","adj_close":58.19},
{"symbol":"K","date":"2021-01-08","adj_close":60.2},
{"symbol":"KHC","date":"2021-01-08","adj_close":33.62},
{"symbol":"PEP","date":"2021-01-08","adj_close":144.18},
{"symbol":"PG","date":"2021-01-11","adj_close":137.85},
{"symbol":"HSY","date":"2021-01-11","adj_close":150.11},
{"symbol":"CLX","date":"2021-01-11","adj_close":193.73},
{"symbol":"COST","date":"2021-01-11","adj_close":364.01},
{"symbol":"MDLZ","date":"2021-01-11","adj_close":57.09},
{"symbol":"K","date":"2021-01-11","adj_close":59.37},
{"symbol":"KHC","date":"2021-01-11","adj_close":32.85},
{"symbol":"PEP","date":"2021-01-11","adj_close":142.09},
{"symbol":"PG","date":"2021-01-12","adj_close":137.05},
{"symbol":"HSY","date":"2021-01-12","adj_close":149.38},
{"symbol":"CLX","date":"2021-01-12","adj_close":194.24},
{"symbol":"COST","date":"2021-01-12","adj_close":364.2},
{"symbol":"MDLZ","date":"2021-01-12","adj_close":57.32},
{"symbol":"K","date":"2021-01-12","adj_close":58.56},
{"symbol":"KHC","date":"2021-01-12","adj_close":32.18},
{"symbol":"PEP","date":"2021-01-12","adj_close":141.43},
{"symbol":"PG","date":"2021-01-13","adj_close":137.26},
{"symbol":"HSY","date":"2021-01-13","adj_close":149.92},
{"symbol":"CLX","date":"2021-01-13","adj_close":193.74},
{"symbol":"COST","date":"2021-01-13","adj_close":366.95},
{"symbol":"MDLZ","date":"2021-01-13","adj_close":57.37},
{"symbol":"K","date":"2021-01-13","adj_close":59.14},
{"symbol":"KHC","date":"2021-01-13","adj_close":32.01},
{"symbol":"PEP","date":"2021-01-13","adj_close":142.59},
{"symbol":"PG","date":"2021-01-14","adj_close":135.8},
{"symbol":"HSY","date":"2021-01-14","adj_close":147.42},
{"symbol":"CLX","date":"2021-01-14","adj_close":195.55},
{"symbol":"COST","date":"2021-01-14","adj_close":362.35},
{"symbol":"MDLZ","date":"2021-01-14","adj_close":57.31},
{"symbol":"K","date":"2021-01-14","adj_close":59.05},
{"symbol":"KHC","date":"2021-01-14","adj_close":32.08},
{"symbol":"PEP","date":"2021-01-14","adj_close":141.76},
{"symbol":"PG","date":"2021-01-15","adj_close":134.78},
{"symbol":"HSY","date":"2021-01-15","adj_close":148.46},
{"symbol":"CLX","date":"2021-01-15","adj_close":197.52},
{"symbol":"COST","date":"2021-01-15","adj_close":362.16},
{"symbol":"MDLZ","date":"2021-01-15","adj_close":57.22},
{"symbol":"K","date":"2021-01-15","adj_close":59.03},
{"symbol":"KHC","date":"2021-01-15","adj_close":31.99},
{"symbol":"PEP","date":"2021-01-15","adj_close":141.39},
{"symbol":"PG","date":"2021-01-15","adj_close":134.78},
{"symbol":"HSY","date":"2021-01-15","adj_close":148.46},
{"symbol":"CLX","date":"2021-01-15","adj_close":197.52},
{"symbol":"COST","date":"2021-01-15","adj_close":362.16},
{"symbol":"MDLZ","date":"2021-01-15","adj_close":57.22},
{"symbol":"K","date":"2021-01-15","adj_close":59.03},
{"symbol":"KHC","date":"2021-01-15","adj_close":31.99},
{"symbol":"PEP","date":"2021-01-15","adj_close":141.39},
{"symbol":"PG","date":"2021-01-19","adj_close":133.6},
{"symbol":"HSY","date":"2021-01-19","adj_close":148.75},
{"symbol":"CLX","date":"2021-01-19","adj_close":196.51},
{"symbol":"COST","date":"2021-01-19","adj_close":354.47},
{"symbol":"MDLZ","date":"2021-01-19","adj_close":57.14},
{"symbol":"K","date":"2021-01-19","adj_close":58.46},
{"symbol":"KHC","date":"2021-01-19","adj_close":32.36},
{"symbol":"PEP","date":"2021-01-19","adj_close":142.06},
{"symbol":"PG","date":"2021-01-20","adj_close":131.93},
{"symbol":"HSY","date":"2021-01-20","adj_close":149.63},
{"symbol":"CLX","date":"2021-01-20","adj_close":196.93},
{"symbol":"COST","date":"2021-01-20","adj_close":361.3},
{"symbol":"MDLZ","date":"2021-01-20","adj_close":57.1},
{"symbol":"K","date":"2021-01-20","adj_close":57.64},
{"symbol":"KHC","date":"2021-01-20","adj_close":32.86},
{"symbol":"PEP","date":"2021-01-20","adj_close":141.33},
{"symbol":"PG","date":"2021-01-21","adj_close":131.01},
{"symbol":"HSY","date":"2021-01-21","adj_close":148.98},
{"symbol":"CLX","date":"2021-01-21","adj_close":197.21},
{"symbol":"COST","date":"2021-01-21","adj_close":362.8},
{"symbol":"MDLZ","date":"2021-01-21","adj_close":56.12},
{"symbol":"K","date":"2021-01-21","adj_close":57.89},
{"symbol":"KHC","date":"2021-01-21","adj_close":32.78},
{"symbol":"PEP","date":"2021-01-21","adj_close":139.61},
{"symbol":"PG","date":"2021-01-22","adj_close":130},
{"symbol":"HSY","date":"2021-01-22","adj_close":148.2},
{"symbol":"CLX","date":"2021-01-22","adj_close":202.35},
{"symbol":"COST","date":"2021-01-22","adj_close":362.3},
{"symbol":"MDLZ","date":"2021-01-22","adj_close":56.25},
{"symbol":"K","date":"2021-01-22","adj_close":58.3},
{"symbol":"KHC","date":"2021-01-22","adj_close":32.91},
{"symbol":"PEP","date":"2021-01-22","adj_close":138.59},
{"symbol":"PG","date":"2021-01-25","adj_close":132.24},
{"symbol":"HSY","date":"2021-01-25","adj_close":147.53},
{"symbol":"CLX","date":"2021-01-25","adj_close":211.96},
{"symbol":"COST","date":"2021-01-25","adj_close":361.88},
{"symbol":"MDLZ","date":"2021-01-25","adj_close":56.87},
{"symbol":"K","date":"2021-01-25","adj_close":59.84},
{"symbol":"KHC","date":"2021-01-25","adj_close":33.75},
{"symbol":"PEP","date":"2021-01-25","adj_close":140.18},
{"symbol":"PG","date":"2021-01-26","adj_close":133.09},
{"symbol":"HSY","date":"2021-01-26","adj_close":149.52},
{"symbol":"CLX","date":"2021-01-26","adj_close":212.99},
{"symbol":"COST","date":"2021-01-26","adj_close":364.98},
{"symbol":"MDLZ","date":"2021-01-26","adj_close":57.59},
{"symbol":"K","date":"2021-01-26","adj_close":60.92},
{"symbol":"KHC","date":"2021-01-26","adj_close":34.39},
{"symbol":"PEP","date":"2021-01-26","adj_close":141.8},
{"symbol":"PG","date":"2021-01-27","adj_close":128.38},
{"symbol":"HSY","date":"2021-01-27","adj_close":146.19},
{"symbol":"CLX","date":"2021-01-27","adj_close":222.18},
{"symbol":"COST","date":"2021-01-27","adj_close":356.39},
{"symbol":"MDLZ","date":"2021-01-27","adj_close":56.42},
{"symbol":"K","date":"2021-01-27","adj_close":62.36},
{"symbol":"KHC","date":"2021-01-27","adj_close":34.74},
{"symbol":"PEP","date":"2021-01-27","adj_close":138.04},
{"symbol":"PG","date":"2021-01-28","adj_close":130.36},
{"symbol":"HSY","date":"2021-01-28","adj_close":148.21},
{"symbol":"CLX","date":"2021-01-28","adj_close":209.57},
{"symbol":"COST","date":"2021-01-28","adj_close":357.06},
{"symbol":"MDLZ","date":"2021-01-28","adj_close":57.12},
{"symbol":"K","date":"2021-01-28","adj_close":60.17},
{"symbol":"KHC","date":"2021-01-28","adj_close":33.96},
{"symbol":"PEP","date":"2021-01-28","adj_close":139.19},
{"symbol":"PG","date":"2021-01-29","adj_close":128.21},
{"symbol":"HSY","date":"2021-01-29","adj_close":145.44},
{"symbol":"CLX","date":"2021-01-29","adj_close":209.46},
{"symbol":"COST","date":"2021-01-29","adj_close":352.43},
{"symbol":"MDLZ","date":"2021-01-29","adj_close":55.44},
{"symbol":"K","date":"2021-01-29","adj_close":58.94},
{"symbol":"KHC","date":"2021-01-29","adj_close":33.51},
{"symbol":"PEP","date":"2021-01-29","adj_close":136.57},
{"symbol":"PG","date":"2021-02-01","adj_close":128.97},
{"symbol":"HSY","date":"2021-02-01","adj_close":145.11},
{"symbol":"CLX","date":"2021-02-01","adj_close":210.02},
{"symbol":"COST","date":"2021-02-01","adj_close":350.52},
{"symbol":"MDLZ","date":"2021-02-01","adj_close":55.25},
{"symbol":"K","date":"2021-02-01","adj_close":58.82},
{"symbol":"KHC","date":"2021-02-01","adj_close":33.25},
{"symbol":"PEP","date":"2021-02-01","adj_close":136.98},
{"symbol":"PG","date":"2021-02-02","adj_close":128.79},
{"symbol":"HSY","date":"2021-02-02","adj_close":147.12},
{"symbol":"CLX","date":"2021-02-02","adj_close":204.23},
{"symbol":"COST","date":"2021-02-02","adj_close":355.58},
{"symbol":"MDLZ","date":"2021-02-02","adj_close":56.16},
{"symbol":"K","date":"2021-02-02","adj_close":58.45},
{"symbol":"KHC","date":"2021-02-02","adj_close":33.16},
{"symbol":"PEP","date":"2021-02-02","adj_close":138.38},
{"symbol":"PG","date":"2021-02-03","adj_close":128.95},
{"symbol":"HSY","date":"2021-02-03","adj_close":146.58},
{"symbol":"CLX","date":"2021-02-03","adj_close":204.59},
{"symbol":"COST","date":"2021-02-03","adj_close":355.21},
{"symbol":"MDLZ","date":"2021-02-03","adj_close":55.28},
{"symbol":"K","date":"2021-02-03","adj_close":58.01},
{"symbol":"KHC","date":"2021-02-03","adj_close":33.01},
{"symbol":"PEP","date":"2021-02-03","adj_close":138.02},
{"symbol":"PG","date":"2021-02-04","adj_close":129.03},
{"symbol":"HSY","date":"2021-02-04","adj_close":147.22},
{"symbol":"CLX","date":"2021-02-04","adj_close":191.65},
{"symbol":"COST","date":"2021-02-04","adj_close":355.85},
{"symbol":"MDLZ","date":"2021-02-04","adj_close":56},
{"symbol":"K","date":"2021-02-04","adj_close":57.87},
{"symbol":"KHC","date":"2021-02-04","adj_close":32.92},
{"symbol":"PEP","date":"2021-02-04","adj_close":139.68},
{"symbol":"PG","date":"2021-02-05","adj_close":129.57},
{"symbol":"HSY","date":"2021-02-05","adj_close":146.6},
{"symbol":"CLX","date":"2021-02-05","adj_close":191.25},
{"symbol":"COST","date":"2021-02-05","adj_close":355.17},
{"symbol":"MDLZ","date":"2021-02-05","adj_close":56.21},
{"symbol":"K","date":"2021-02-05","adj_close":58.03},
{"symbol":"KHC","date":"2021-02-05","adj_close":33.8},
{"symbol":"PEP","date":"2021-02-05","adj_close":140.96},
{"symbol":"PG","date":"2021-02-08","adj_close":129.17},
{"symbol":"HSY","date":"2021-02-08","adj_close":149.33},
{"symbol":"CLX","date":"2021-02-08","adj_close":190},
{"symbol":"COST","date":"2021-02-08","adj_close":359.83},
{"symbol":"MDLZ","date":"2021-02-08","adj_close":56.02},
{"symbol":"K","date":"2021-02-08","adj_close":57.74},
{"symbol":"KHC","date":"2021-02-08","adj_close":33.91},
{"symbol":"PEP","date":"2021-02-08","adj_close":140.4},
{"symbol":"PG","date":"2021-02-09","adj_close":128.67},
{"symbol":"HSY","date":"2021-02-09","adj_close":149.62},
{"symbol":"CLX","date":"2021-02-09","adj_close":187.35},
{"symbol":"COST","date":"2021-02-09","adj_close":359.56},
{"symbol":"MDLZ","date":"2021-02-09","adj_close":55.5},
{"symbol":"PEP","date":"2021-02-09","adj_close":139.6},
{"symbol":"KHC","date":"2021-02-09","adj_close":33.71},
{"symbol":"K","date":"2021-02-09","adj_close":57.64}]
Here is a sample including company ticker selector:
Presentator.js:
export function Presentator() {
const [data, setData] = useState([]);
const [ticker, setTicker] = useState('');
useEffect(() => {
const fetchData = async () => {
/* DO ACTUAL FETCH FROM SERVICE */
const result = await Promise.resolve(response);
setData(result);
}
fetchData();
}, []);
const handleTickerChange = (event) => {
setTicker(event.target.value);
}
const getTickerData = (ticker) => {
return data.filter(item => item.symbol.toLowerCase() === ticker.toLowerCase());
};
const getTickerDropdownValues = () => {
const set = new Set();
data.forEach(item => {
if (!set.has(item.symbol)) {
set.add(item.symbol);
}
});
return Array.from(set);
}
const getTickerDropdown = () => {
const options = getTickerDropdownValues();
return (
<select value={ticker} onChange={handleTickerChange}>
{options.map(option => {
return (
<option key={option} value={option}>{option}</option>
);
})}
</select>
);
}
return (
<>
{getTickerDropdown()}
<Graph data={getTickerData(ticker)} />
</>
);
}
Graph.js:
export function Graph(props) {
const { data } = props;
const getChartData = () => {
const labels = [];
const series = [];
data.forEach(item => {
labels.push(item.date);
series.push(item.adj_close);
});
return {
labels: labels,
series: [series]
};
}
// Add your graph configuration here
const chartOptions = {
// width: 2000,
height: 400,
// scaleMinSpace: 20
};
return (
<ChartistGraph data={getChartData()} options={chartOptions} type="Line" />
);
}
Basically, the Presentator handles the initial fetching of the data and the logic to split the data by ticker. Then, the Graph component handles the visualization of the specific ticker data itself.
You can check a working example at this codesandbox.
You don't need to store anything more in the state than the data itself. In our case we're also storing the selected value for the ticker dropdown. Everything else can be calculated.
In the getChartData function you can do further filtering and manipulation of the data as for example presenting only the last 10 records(dates) instead of the whole set.
If I understand you correctly, you need to display the adj_close values for each date, grouped by symbol. Is that correct?
First, make changes to your state:
const [chartData, setChartData] = useState({
labels: [],
series: []
});
You can group the response by symbol like this:
const symbols = response.reduce((map, value) => {
if (map.has(value.symbol)) {
map.set(value.symbol, [...map.get(value.symbol), value]);
} else {
map.set(value.symbol, [value]);
}
return map;
}, new Map())
Then get the unique dates:
const dates = [...new Set(response.map(r => r.date))]; // note: it doesn't sort dates!
Then construct the series multi-dimensional array. For each symbol, you include the adj_close values for every date.
const series = Array.from(symbols).map(value => {
const valuesForSymbol = value[1];
return dates.map(date => {
const valueForDate = valuesForSymbol.find(v => v.date === date);
return valueForDate.adj_close;
});
});
Set the state:
setChartData({labels: dates, series });
And finally, display the chart like this:
<ChartistGraph data={chartData} options={options} type="Line" />
Full example here.
I have rewritten you code check if its work for your situation
import React, { useState, useEffect } from "react";
import ChartistGraph from 'react-chartist';
export default function Graph() {
const [data, setData] = useState({
chart: {
label: [],
series: []
},
dataBySymbols: {},
symbols: [],
select: "",
});
const getData = () => {
setTimeout(() => {
const _tmp = new Set();
const dataBySymbols = {};
response.forEach(item => {
_tmp.add(item.symbol);
if (!dataBySymbols.hasOwnProperty(item.symbol)) {
dataBySymbols[item.symbol] = {
label: [],
series: [
[]
]
};
}
dataBySymbols[item.symbol]['label'].push(item.date);
dataBySymbols[item.symbol]['series'][0].push(item.adj_close);
});
const copy = {...data};
copy['dataBySymbols'] = dataBySymbols;
copy['symbols'] = Array.from(_tmp);
copy['chart'] = dataBySymbols[copy['symbols'][0]];
setData(copy);
}, 3000)
}
useEffect(() => {
getData()
}, [])
function onSelectChange(evt) {
const copy = {...data};
copy['select'] = evt.target.value;
copy['chart'] = copy.dataBySymbols[evt.target.value]
setData(copy);
}
const options = {
width: 500,
height: 400
};
return (
<div>
<select value={data.select} onChange={onSelectChange}>
{data.symbols.map(option => {
return (
<option key={option} value={option}>{option}</option>
);
})}
</select>
<ChartistGraph data={data.chart} options={options} type="Line" />
</div>
);
};
export default function App() {
return (
<Graph />
);
}
Here working example

How to save data in an array inside state in react js

I have TextField and FlatButton inside the Dialog. I want to save complete task list in an array which I defined in a state.
this.state = {
open: false,
todos: [{ id: -1, text: "", completed: false }],
notetext: ""
};
I am able to get text of TextField from the state. I want to save task in an array on clicking of FlatButton. I have handleCreateNote function which is attached on tap on FlatButton.
I don't know what is the way to add task in an array. Can anyone help me what is the way in the react ?
const AppBarTest = () =>
<AppBar
title={strings.app_name}
iconClassNameRight="muidocs-icon-navigation-expand-more"
style={{ backgroundColor: colors.blue_color }}
/>;
class App extends Component {
constructor(props) {
injectTapEventPlugin();
super(props);
this.state = {
open: false,
todos: [{ id: -1, text: "", completed: false }],
notetext: ""
};
this.handleChange = this.handleChange.bind(this);
}
handleOpen = () => {
this.setState({ open: true });
};
handleClose = () => {
this.setState({ open: false });
};
handleCreateNote = () => {
console.log(this.state.notetext);
};
handleChange(event) {
this.setState({ [event.target.name]: event.target.value });
}
render() {
return (
<MuiThemeProvider>
<div>
<AppBarTest />
<FloatingActionButton
style={styles.fab}
backgroundColor={colors.blue_color}
onTouchTap={this.handleOpen}
>
<ContentAdd />
</FloatingActionButton>
<Dialog
open={this.state.open}
onRequestClose={this.handleClose}
title={strings.dialog_create_note_title}
>
<TextField
name="notetext"
hintText="Note"
style={{ width: "48%", float: "left", height: 48 }}
defaultValue={this.state.noteVal}
onChange={this.handleChange}
/>
<div
style={{
width: "4%",
height: "48",
backgroundColor: "red",
float: "left",
visibility: "hidden"
}}
/>
<FlatButton
label={strings.create_note}
style={{ width: "48%", height: 48, float: "left" }}
onTouchTap={this.handleCreateNote}
/>
</Dialog>
</div>
</MuiThemeProvider>
);
}
}
export default App;
First create a copy of existing state array, then use array.push to add a new data, then use setState to update the state array value.
Like this:
handleCreateNote = () => {
let todos = [...this.state.todos]; //creating the copy
//adding new data
todos.push({
id: /*unique id*/,
text: this.state.notetext,
completed: false
});
//updating the state value
this.setState({todos});
};
Check this answer for details about "..." --> What do these three dots in React do?
MDN: Spread Operator
Update:
Instead of spread operator you can also use slice(), that will also return a new array, the key point is we need to create a copy of state array (before doing any change) by using any method.
Check this snippet:
let a = [{key: 1}, {key: 2}];
let b = [...a];
console.log('b', b);
you can use concat to create a new array:
this.setState({
todos: [].Concat(this.state.todos, {id, text, complete})
})

Categories