1
I am creating a dynamic table, in which I save the row information in the localStorage. To render the table, I give a getItem
in localStorage, a setRows
on a map in the variable rows
.
const [rows, setRows] = useState([]);
const rowsLS = JSON.parse(localStorage.getItem('rows')) || [];
useEffect(() => {
setRows(rowsLS);
}, [rowsLS]);
I wish that when the user adds a new Row, the Component will redecorate it too, and this is working, but the console is returning the following error:
Maximum update Depth exceeded. This can happen when a Component calls setState Inside useEffect, but useEffect either doesn’t have a dependency array, or one of the dependencies changes on Every render.
I would like to know what is causing this error and how to avoid it without changing the operation
it is difficult to know only by this stretch, but, there is already redundancy in your code, because you could pass the value
localStorage.getItem('rows')
directlyconst [rows, setRows] = useState(localStorage.getItem('rows') || []);
without the need to create a constant in his code and I think (there’s no way to know exactly) that he complains about theuseEffect
, being called several times, in case you can take it away from there for now with the change above– novic
By doing this way, if the Storage location changes the variable will also change and thus render the new column?
– Luis von Rondow
Come on: so the way I told you he takes the last update that’s on
localStorage
and plays in the component status variable. That is, all updates inrows
you need to pass to thelocalStorage
also so that when entering this component also always have the last update. So then you can use theuseEffect(() => { localStorage.setItem('rows', JSON.stringify(rows)) }, [rows]);
where when changing Rows it goes there and adds the last update in localStorage? get this– novic