Home > Enterprise >  How do I make a react app that preserves the data on refresh
How do I make a react app that preserves the data on refresh

Time:05-22

I've built a simple expense tracker app on react like such

How do I now make it such that the expenselog object avoids reverting back to the default state on refreshing but preserves the new expenses that were added by the client

import { useState } from 'react';

function App() {

  var [expenselog,setExpenselog] = useState([
    {
      name: "Expense1",
      amount: 1000
    },
    {
      name: "Expense2",
      amount: 100
    }
  ]);

  var [count, setCount] = useState(0);
  var [name, setName] = useState("");

  const inputChangeHandler = (e) => { 
    setName(e.target.value);
  }

  const inputChangeHandler2 = (e) => { 
    setCount(e.target.value);
  }
  
  const clickHandler = () => { 
    if (name === "" || count === "" || count <= 0) {
      alert("Please enter a name and amount");
    } else {
    setExpenselog([...expenselog, {name: name, amount: count}]);
    document.querySelector('.inputField').value = "";
    document.querySelector('.inputField2').value = 0;
    setCount(0);
    setName("");
    }
  }
  var sum=0;

  for (var i = 0; i < expenselog.length; i  ) {
    sum = parseInt(sum)   parseInt(expenselog[i].amount);
  }

  return (
    <div className="App">
      <input onChange={inputChangeHandler} className='inputField'/>
      <input type={"number"} onChange={inputChangeHandler2} className='inputField2'/>
      <button onClick={clickHandler}>Add Expense</button>
      <br/>
      <h1>Total money spent : {sum}</h1>
      {expenselog.map(expense => <p>{expense.name} - {expense.amount}</p>)}
    </div>
  );
}

export default App;

CodePudding user response:

you need to write and read from browser's cookies or local storage

using a simple library like http://wisembly.github.io/basil.js/ would help

CodePudding user response:

Select betweeon localStorage or sessionStorage.
localStorage can be shared between tabs, and will persist if you close the tab.
sessionStorage can not be shared between tabs. When you close tab, it will disappear.

CodePudding user response:

Like the previous answer mentioned, you're going to need to persist the state of your app across react's hot-reloading mounts. You can opt for a state management library, write to a local text file with the help of an external library, or utilize the browsers local storage API.

I'd recommend using the local storage API with this react hook.

  • Related