persist state after page refresh in React using local storage
You've fallen into a classic React Hooks trap - because using useState()
is so easy, you're actually overusing it.
If localStorage
is your storage mechanism, then you don't need useState()
for that AT ALL. You'll end up having a fight at some point between your two sources about what is "the right state".
All you need for your use-case is something to hold the text that feeds your controlled input
component (I've called it leadText
), and something to hold your display
boolean:
const [leadText, setLeadText] = useState('')
const [display, setDisplay] = useState(false)
const localStoredValues = JSON.parse(window.localStorage.getItem('localValue') || '[]')
const handleChange = (event) => {
const { name, value } = event.target
setLeadText(value)
}
const saveBtn = () => {
const updatedArray = [...localStoredValues, leadText]
localStorage.setItem('localValue', JSON.stringify(updatedArray))
setDisplay(false)
}
const displayBtn = () => {
setDisplay(true)
}
const displayLocalItems = localStoredValues.map((item) => {
return <li key={item}>{item}</li>
})
return (
<main>
<input name="inputVal" value={leadText} type="text" onChange={handleChange} required />
<button onClick={saveBtn}> Save </button>
<button onClick={displayBtn}>Display Leads</button>
{display && <ul>{displayLocalItems}</ul>}
</main>
)
Losing useState Value on Refresh in React.js
const getProductListingData = async () => {
try {
const response = await fetch("http://localhost:8000/productListing");
const data = await response.json();
if (data) {
setLoading(false);
setProducts(data.products);
// call this function after you are getting list of products
getProductID(data.products);
} else {
setProducts("PRODUCT LISTING DATA NOT FOUND");
}
} catch (error) {
console.log(error);
}
};
const getProductID = (tempProducts) => {
let foundProduct = {};
foundProduct = tempProducts.find((item) => {
return item.id === parseInt(id);
});
setSingleProduct(foundProduct);
};
How to save state of React page on reload or redirecting back/ forward?
you can use localStorage.setItem
and localStorage.getItem
for accessing local storage. like:
class CustomerList extends Component {
state = {
isLoading: true,
users: [],
error: null,
customerID: null
};
componentDidMount() {
if(!localStorage.getItem('customerlist-data')) {
fetch('http://localhost:8080/entity/getEntityByFeatureGroup/'+this.customerID)
.then(response => response.json())
.then(data => {
this.setState({
users: data,
isLoading: false,
});
localStorage.setItem('customerlist-data', data);
}
).catch(error => this.setState({ error, isLoading: false }));
enter code here}
}
render() {
var logTable = this.props;
console.log(logTable);
var customerColumnList = this.props;
this.customerID = customerColumnList.location.aboutProps.id.featureGroupID;
var headerName = customerColumnList.location.aboutProps.name.logTable.headerName;
const { isLoading, users, error } = this.state;
return (....
localStorage is saving my data but after refresh is reseting and empty it
You should be loading todos from localStorage on the Component mount if they are available in localStorage like this,
const loadedTodos = localStorage.getItem("todos")
? JSON.parse(localStorage.getItem("todos"))
: []; // new
const [todos, setTodos] = useState(loadedTodos); // updated
And then you don't have to mutate the state using setTodos(loadedTodos) in the useEffect
.
Just remove this useEffect , from the code:
// that useEffect should be removed
useEffect(() => {
const json = window.localStorage.getItem("todos");
const loadedTodos = JSON.parse(json);
if (loadedTodos) {
setTodos(loadedTodos);
}
}, []);
You can check this in the working CodeSandbox as well.
Related Topics
Display Current Date in Dd/Mm/Yyyy Format
How to Change Size of Mat-Icon on Angular Material
How to Prevent Form to Reload Page After Onsubmit
How to Run HTML File on Localhost
How to Stop the Iframe from Constantly Reloading After Setinterval (Jquery)
How to Get the Value by a Key from a Super Nested Json
Is There Any Memory Limit for Google Chrome Browser
Call Function Onpress React Native
Most Efficient Method to Groupby on an Array of Objects
How to Convert Raw Mp3 Binary into Blob Url and Play It in Audio Tag
Safari Browser Audio.Play() Is Not Working
Nosuchelementerror: Unable to Locate Element - Selenium Webdriver Using JavaScript
Hierarchical Json from Flat With Parent Id
Angular Conditional Readonly/Disable on Input Fields
React Native Init Android,Ios and App Folder Missing
Javascript or Jquery Browser Back Button Click Detector