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 make setting state with useEffect() to run on page refresh?
Try this:
(In your Photo page)
const [photoArr, setPhotoArr] = useState(null);
useEffect(() => {
if(photoData.length) setPhotoArr(photoData) // If not empty, set the Arr
},[photoData]} // We listen to photoData's change
On page load, there aren't any data in your photoData, and as it pass down to Photo component, react remembers that state.
But with useEffect listen to photoData's change, we can setPhotoArr once the getPhotos function got the data back.
Unable to render React page after refresh, instead showing raw data
The issue is how you have configured your server.js file
app.use('/teacher', authRoutes);
app.use('/class', classRoutes);
app.get('/', (req, res, next) => {
res.sendFile(path.resolve(__dirname, "../docs/index.html"))
})
Now imagine you are sending request to your server to fetch the data in url /teacher
now it is doing it's job perfectly fine. Because, it would come across the first line and send you the raw json and be done with it.
One solution would be to keep all your api modules in an '/api' appended path. So, they don't conflict with your regular routing.
app.use('/api/teacher', authRoutes);
app.use('/api/class', classRoutes);
app.get('/', (req, res, next) => {
res.sendFile(path.resolve(__dirname, "../docs/index.html"))
})
This should solve your issue.
EDIT:
Last route should always return home page. So, a star is needed in path-matching
app.get('/*', (req, res, next) => {
res.sendFile(path.resolve(__dirname, "../docs/index.html"))
})
Related Topics
"Invocation Context" and "Execution Context" in JavaScript: Are We Talking of the Same Thing
Highlight Selected Node, Its Links, and Its Children in a D3 Force Directed Graph
How to Read from Chrome's Console in JavaScript
Hide Select Option in Ie Using Jquery
Window.Open and Pass Parameters by Post Method
Avoid Window Jump to Top When Clicking #-Links
Drawing Rotated Text on a HTML5 Canvas
JavaScript to Get Paragraph of Selected Text in Web Page
Javascript/HTML Storage Options Under File Protocol (File://)
Createelement VS. Createelementns
Access JavaScript Nested Objects Safely
How to Remove a Buggy Service Worker, or Implement a "Kill Switch"
Get Caret (Cursor) Position in Contenteditable Area Containing HTML Content
Migrating Angularjs to Angular 4,5 (With Demo)
How to Apply CSS to the Elements Within an Iframe
How to Bind the HTML <Title> Content in Vuejs
Dynamically Populating Drop Down List from Selection of Another Drop Down Value