I’m new to react and am having a issue when trying to reset array back to its initial state. The array does update correctly when applying the changes, however no re-render is triggered.
I tried to put in a completely new array so that it was obvious that it was a new array being put it but that didn’t work either.
Here are the relevant parts of the code:
const handleClear = (
setInkomsten: React.Dispatch<React.SetStateAction<any[]>>,
setUitgaven: React.Dispatch<React.SetStateAction<any[]>>,
initialInkomsten: any[],
initialUitgaven: any[],
setDummy: React.Dispatch<React.SetStateAction<number>>
) => {
console.log("Clear button clicked");
localStorage.clear();
// Create new arrays by copying the initial values
const newInkomsten = [...initialInkomsten];
const newUitgaven = [...initialUitgaven];
// Update state with new arrays
setInkomsten(newInkomsten);
setUitgaven(newUitgaven);
// Set localStorage with initial values
localStorage.setItem("Inkomsten", JSON.stringify(newInkomsten));
localStorage.setItem("Uitgaven", JSON.stringify(newUitgaven));
console.log("Local storage:", localStorage);
// Force a re-render
setDummy(prev => prev + 1);
};
export default handleClear;
Relevant parts of the main code:
function App() {
const initialInkomsten = [
"Inkomsten",
"Boodschappen",
"Dierenvoeding",
"Activiteiten",
"Gokken",
];
const initialUitgaven = [
"Uigaven",
"Kleren",
"Dierenvoeding",
"Spelen",
"Gokken",
];
const [dummy, setDummy] = useState<number>(0);
const [inkomsten, setInkomsten] = useState(initialInkomsten);
const [uitgaven, setUitgaven] = useState(initialUitgaven);
Relevant part of the helper function:
const InputContainer: React.FC<InputContainerProps> = ({
information,
color,
storageKey,
}) => {
const [inputValue, setInputValue] = useState<string[]>(() => {
const savedInput = localStorage.getItem(storageKey);
return savedInput ? JSON.parse(savedInput) : information;
});
useEffect(() => {
localStorage.setItem(storageKey, JSON.stringify(inputValue));
console.log(inputValue);
}, [inputValue, storageKey]);
I tried completely renewing the array with no success. I also added a dummy state that would get incremented when the clear button would be pressed but this also doesn’t trigger a re render.
I tried directly putting the new arrays in Local Storage and logging them which came back successful but still no rerender
Ziaad is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.
7