Estoy luchando por modificar un objeto similar a JSON con la propiedad setState (desde un enlace useState). Me gustaría agregar elementos a etiquetas y matrices de datos al mismo tiempo.
const dataInit = { labels: [ 'January', 'February', 'March', 'April', 'May', 'June', ], datasets: [{ label: 'My First dataset', backgroundColor: 'rgb(255, 99, 132)', borderColor: 'rgb(255, 99, 132)', data: [0, 10, 5, 2, 2, 30, 49,80], }] };Aquí está la inicialización de mi enlace useState con un intento que no funciona:
const [graphData, setGraphData] = useState(dataInit) setGraphData(prevState => ({ ...prevState, labels: prevState.labels.concat(["hey"]), datasets: prevState.datasets[0].data.concat([3]) }) )Gracias por ayudar
Devuelva siempre un nuevo objeto a los accesorios anidados que son objetos, mientras establece el estado. Lo que hace concat es agregar un nuevo valor al objeto existente. Prueba algo como:
const [graphData, setGraphData] = useState(dataInit) setGraphData(prevState => { let _datasets = [...prevState.datasets]; _datasets[0].data = [..._datasets[0].data, ...data]; return { ...prevState, labels: [...prevState.labels, "hey"], //new array returns with previous and new value datasets: _datasets } })