Save State When Refresh Page - Reactjs

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



Leave a reply



Submit