skip to Main Content

why does my localstorage resets to empty whenever i refresh?

i want to save the data on localstorage which is also passed to my redux state but i cant

const getLocalStorage = () => {
    const oldExpenses = JSON.parse(window.localStorage.getItem("ADDED_EXPENSES"));
    if (oldExpenses) {
        return oldExpenses;
    } else {
        return [];
    }
};
const loadedExpenses = getLocalStorage();
const Expense = () => {
    const dispatch = useDispatch();
    console.log(getLocalStorage());
    useEffect(() => {
        dispatch(loadExpenses(loadedExpenses));
    }, [dispatch]);
    const isnew = useSelector(isNew);

    const nonFormattedItems = useSelector(expenses);
    console.log(nonFormattedItems);

    const formattedItems = nonFormattedItems.map((expense) => {
        const dt = expense.date;
        const stDate = new Date(dt);
        const newExpense = { ...expense, date: stDate };
        return newExpense;
    });


    const updateLocalStorage = () => {
        window.localStorage.setItem(
            "ADDED_ITEMS",
            JSON.stringify(nonFormattedItems)
        );
    };

    useEffect(() => {
        updateLocalStorage();
    }, [nonFormattedItems]); // nonFormattedItems is used as a dependency here
    console.log(nonFormattedItems);
    const newExpenseHandler = (expense) => {
        if (isnew) {
            dispatch(addExpense(expense));
        }
    };

i tried to call this directly instead of using useEffect:

dispatch(loadExpenses(loadedExpenses));

but this gave me infinite loop.

2

Answers


  1. Why you dont try redux-persist package?

    Login or Signup to reply.
  2. I actually came across this issue today as well working on a chrome extension

    You should do it like this const obj = localStoraget.getItem('item')
    then -> const parsedObj = JSON.parse(obj)

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search