Mohammad Aziz
Posted on February 18, 2019
Yesterday, while I was writing a post which took me 45 minutes to finish, someone from my family came and accidentally pressed the back button of my browser. At that point, I did not understand the consequence and I thought if I will go forward all of the content written will be there. Unfortunately, this is not the case for sites like Hashnode and Dev.to.
Shocking Period
After returning back to the page where I was writing my post I saw what you'll normally see when you click on write a post button. A page with no content. That is when I first get the sense something terrible has happened. For confirmation of the catastrophe I refreshed the page and after that, I started crying inside.
All of the work that I have done for 45 minutes was gone. ðŸ˜
Current Solution
At the current scenario, to save your post periodically you will have to click on save post every time you want to save the current state of your draft. I certainly understand why the platform creators have chosen this way of implementation. Two simple reasons are there:
- Reduce server load time and therefore...
- Reduce server bills
Well, we can certainly go this way of implementation but I think there is a better way to do this.
My Solution
localStorage
is one way to improve it. localStorage
is a key/value Web Storage API. In which we can store the data of our post. The best part of localStorage is that data in it persist even after tab close or refresh.
Since Dev.to uses React my implementation is React specific but the general idea will be the same for other frameworks on other platforms. The implementation is on Codesandbox and you can view it from the link below.
At initial render, I'm checking whether there is some content already present or not. If there is, set the value of textarea
to the previously saved value.
...
React.useEffect(() => {
const content = localStorage.getItem("content") || "";
setContent(content);
}, []);
...
<textarea
value={content}
onChange={handleChange}
/>
The handleChange
function:
function handleChange(event) {
const value = event.target.value;
setContent(value);
}
Every call to setContent
will trigger useEffect
hook which throttles setting the value of our content in the localStorage
. While throttling is not necessary but instead of localStorage
if there would have been an API then throttling definitely make sense in that case.
const throttled = throttle((content = "") => {
localStorage.setItem("content", content);
}, 500);
...
React.useEffect(() => throttled(content));
...
Yes, there are some corner cases that I hadn't covered in this implementation for the sake of keeping this post simple.
Please let me know @ben about your thoughts on this and how can we improve?
Posted on February 18, 2019
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.