Techiio-author
Started by Jake WiliamsSep 25, 2021

Open
My data in useState gets lost when i reload my page in react

4 VIEWES 0 LIKES 0 DISLIKES SHARE
0 LIKES 0 DISLIKES 4 VIEWES SHARE

const [credentials, setCredentials] = useState({name:"", password:""});

1 Replies

Techiio-commentatorArchana Behera replied 2 months ago2 likes0 dislikes

You are setting your initial state name and password as an empty string. when you refresh your page state is come back to the initial value which is n empty string. if you want to keep your state data after the page refresh, then you have to store that data in local storage.

import React,  from "react";
const App=()=>{
 const [count, setCount] = React.useState(1); 
React.useEffect(() => { setCount(JSON.parse(window.localStorage.getItem('count'))); }, []); 
 React.useEffect(() => { window.localStorage.setItem('updated count', count); }, [count]); 
const next = () => setCount(count+1);
const previous = () => setCount(count-1);
 return (
 <div>
 <h1> Count {count} </h1>
 <button onClick={next}>next</button>
 <button onClick={previous}>previous</button> 
</div> 
);} 
export Default App;

You must be Logged in to reply
Techiio-logo

Techiio is on the journey to build an ocean of technical knowledge, scouring the emerging stars in process and proffering them to the corporate world.

Follow us on:

Subscribe to get latest updates

You can unsubscribe anytime from getting updates from us
Developed and maintained by Wikiance
Developed and maintained by Wikiance