How to save data in react js ?.
React is a Javascript Framework and it work in frontend. Many times we need to persist the state of application in front end, this article will explain how to persist state of React application or save data in React application. For storing data in backend we have database, when we start a request from react application to backend to get some data from backend then response can be stored in Components state. But Component state become more complex in case of inter component communication. For this React have simplified solution to store data in native local storage of browser. There is no external package or library needed for this. React have local storage and session storage to store data in browser.
1. Local Storage :
Keyword localStorage is used for local storage. Browser compatibility can be checked from official page Official Local Storage .
It’s very easy to use , as localStorage variable available in react without importing any library. It has four built in Function to store, retrieve and remove data.
-> To store value , it has setter function
localStorage.setItem("key","value");
Here here ‘key’ is key to store and retrieve data and ‘value’ is data. Data must be in string format, if there is JSON object then that needs to be convert in string. Below is an example:
class App extends React.Component { constructor(props) { super(props); this.state = { val: localStorage.getItem('key'), } } save=(e)=>{ localStorage.setItem("key", this.state.val); alert('Saved'); } render(){ return ({ this.setState({val:event.target.value}); } } />); } }
-> To get value, it has getter function e.g.
localStorage.getItem("key");
here key is the name which is used in storing data.JSON string need to parse in JSON object. Below is example:
class App extends React.Component { constructor(props) { super(props); this.state = { val: localStorage.getItem('key'), } } save=(e)=>{ localStorage.setItem("key", this.state.val); alert('Saved'); } show=(e)=>{ let value = localStorage.getItem("key"); this.setState({val:value}); alert('Stored value is ' + value); } render(){ return ({ this.setState({val:event.target.value}); } } />); } }
-> To remove data, it two function(localStorage.removeItem(‘key’) and localStorage.clear())
To remove specific data then use localStorage.removeItem(‘key’).
To remove all data then use localStorage.clear().
Below is complete example of local storage.
class App extends React.Component { constructor(props) { super(props); this.state = { val: localStorage.getItem('key'), } } save=(e)=>{ localStorage.setItem("key", this.state.val); alert('Saved'); } remove=(e)=>{ localStorage.removeItem("key"); alert('Removed'); } show=(e)=>{ let value = localStorage.getItem("key"); this.setState({val:value}); alert('Stored value is ' + value); } render(){ return ({ this.setState({val:event.target.value}); } } />); } }
Local Storage data will persist always even after closing browser. When we open browser then data will be there browser. You can find its source code from github Local Storage repository .
2. Session Storage :
Keyword sessionStorage is used for session storage. Browser compatibility can be checked from official page official session storage.
It is same as local storage, only the difference is that it has the expiration of data. Saved data will be empty on closing the browser however there will no intact on refreshing or tab closing. Session storage is have same function as of local storage. Source Code is available on GitHub
Below is the example of Session Storage.
class App extends React.Component { constructor(props) { super(props); this.state = { val: sessionStorage.getItem('key'), } } save=(e)=>{ sessionStorage.setItem("key", this.state.val); alert('Saved'); } remove=(e)=>{ sessionStorage.removeItem("key"); alert('Removed'); } show=(e)=>{ let value = sessionStorage.getItem("key"); this.setState({val:value}); alert('Stored value is ' + value); } render(){ return ({ this.setState({val:event.target.value}); } } />); } }
Related Article
Leave a Reply
Want to join the discussion?Feel free to contribute!
thanks for helping
What does it mean to increase friction? I would be really useful if anyone can react to that concern. I’m caught with this difficulty for previous 7 days and I’m not able to uncover properties answer for that issue. Any response will be very appreciated. Thank you extremely considerably and have a great day. Apologies for my weak english language. Cheers !
Have you noticed the news has changed its approach recently? What once seemed like a never discussed issue has become more prevelant. Its that time to chagnge our stance on this though.
Wonderful job right here. I definitely enjoyed what you had to say. Keep going because you certainly bring a new voice to this subject. Not many people would say what youve said and still make it interesting. Properly, at least Im interested. Cant wait to see additional of this from you.
Dobry przyjaciel widzi pierwsza lze, lapie druga i powstrzymuje trzecia.
Youre so right. Im there with you. Your blog is definitely worth a read if anybody comes throughout it. Im lucky I did because now Ive received a whole new view of this. I didnt realise that this issue was so important and so universal. You surely put it in perspective for me.
Wonderful write-up, Ive bookmarked this site so hopefully Ill discover more on this topic in the future!
Nie otrzymujemy krotkiego zycia, lecz je takim czynimy. Nie brakuje nam czasu, lecz trwonimy go. – Seneka
Nice post, thanks. I signed up to RSS on this blog.
I think this is one of the most important information for me. And i am glad reading your article. But want to remark on some general things, The web site style is ideal, the articles is really nice : D. Good job, cheers
My pal and I have been just talking about this particular topic, she actually is constantly trying to prove me completely wrong! I am going to present her this write-up not to mention rub it in a little!
Hello 🙂 I bookmarked this site. Thanks heaps for this!…
Muchas gracias. ?Como puedo iniciar sesion?
Super! Great this typography carry on as usual
A client may ever be in the spy of morality but module ever rise above a cats glossa
Really appreciate this post. It’s hard to sort the good from the bad sometimes, but I think you’ve nailed it!
Thank you for that smart critique. Me & my neighbour were preparing to do some research about that. We obtained a great book on that matter from our local library and most books exactly where not as influensive as your info. I am extremely glad to see such information which I was searching for a lengthy time.
Greetings! Very helpful advice in this particular article!
It’s the little changes that produce the largest changes.
Thanks for sharing!
Your style is so unique in comparison to other people I have read stuff
from. I appreciate you for posting when you have the opportunity, Guess I’ll just bookmark this
web site.
Thanks for the sensible critique. Me & my neighbour were making ready to do a little analysis about that. We obtained a good e book on that matter from our local library and most books where not as influensive as your information. Im very glad to see such information which I was searching for a long time.This made very glad! Anyway, in my language, there usually are not much good source like this.
І got this ԝeb page from mүy friеnd whoo shareⅾ with me concerning
this web page and at thee moment this ime I amm visiting
this weeb page and гeading verry informative articles here.
Hello it’s me, I am also visiting this website regularly,
this site is actually pleasant and the visitors are really sharing fastidious thoughts.
A fascinating discussion is worth comment.
I believe that you need to publish more on this subject matter, it might not be a taboo
subject but typically people don’t discuss such subjects.
To the next! Best wishes!!
Hi there, I discovered your website by the use of Google at the same time as searching for a comparable subject, your web site came up,
it appears good. I’ve bookmarked it in my google bookmarks.
Hi there, just become alert to your weblog via Google, and located that it is really informative.
I’m going to be careful for brussels. I will be grateful should you
continue this in future. A lot of other people
might be benefited from your writing. Cheers!
Hi there, everything is going well here and ofcourse every one is sharing information, that’s truly good,
keep up writing.
You are so cool! I don’t believe I have read through a single thing like this before.
So nice to find somebody with unique thoughts on this topic.
Seriously.. thank you for starting this up.
This site is one thing that is required on the web,
someone with a little originality!
How is it that just anyone can create a blog and get as popular as this? Its not like youve said anything incredibly impressive more like youve painted a pretty picture about an issue that you know nothing about! I dont want to sound mean, right here. But do you actually think that you can get away with adding some quite pictures and not genuinely say anything?
Its like you read my mind! You seem to know
a lot about this, like you wrote the book in it or something.
I think that you could do with a few pics to drive the
message home a bit, but instead of that, this is great blog.
A fantastic read. I’ll definitely be back.
It’s nearly impossible to find experienced people on this topic,
but you sound like you know what you’re talking about!
Thanks
Greetings! Very helpful advice within this post! It is the
little changes that make the largest changes. Many thanks for sharing!
I like the valuable info you provide in your articles. I will bookmark your weblog and check again here frequently.
I’m quite certain I’ll learn many new stuff right here!
Good luck for the next!
Remarkable! Its truly amazing post, I have got much clear idea about
from this piece of writing.
Thank you for the good writeup. It in fact was a amusement account it.
Look advanced to more added agreeable from you! By the way, how could we communicate?
connect on info@ymento.com
I don’t even know the way I finished up right here, but I thought this post was great.
I do not recognise who you’re but certainly you’re going to a famous blogger when you are not already.
Cheers!
Hello there! I just wish to offer you a big thumbs up for your excellent information you
have got right here on this post. I am coming back to your website for more
soon.
Hmm is anyone else encountering problems with the
pictures on this blog loading? I’m trying to figure out if its a problem on my end or if it’s the blog.
Any feed-back would be greatly appreciated.
Great article! This is the type of information that are
supposed to be shared across the net. Disgrace on Google for now not positioning this submit higher!
Come on over and seek advice from my website . Thank you =)
After looking into a number of the articles on your web site,
I truly appreciate your technique of writing a blog. I added it
to my bookmark webpage list and will be checking back soon.
Please check out my website as well and let me know
what you think.
Hi Dear, are you in fact visiting this site regularly, if
so after that you will absolutely obtain nice know-how.
I simply could not leave your site before suggesting that I actually
enjoyed the usual info an individual provide for your visitors?
Is gonna be back ceaselessly in order to investigate cross-check new posts
I do not even know how I ended up here, but I thought this post
was good. I don’t know who you are but definitely you are going to a famous blogger if you
aren’t already 😉 Cheers!
hey buddy, I ran across this web page from yahoo and start reading several of your other content. They are stunning. Pleasee continue this great work. Cheers,
Hey! Just dropped by to write great web site. Continue with the great work youre doing!
I don’t even know how I ended up here, but I thought this post was good.
I don’t know who you are but certainly you’re going to a famous blogger if you aren’t already 😉 Cheers!
Whoa! This blog looks just like my old one!
It’s on a totally different subject but it has pretty much the same page layout and
design. Superb choice of colors!
Does your site have a contact page? I’m having trouble locating it but,
I’d like to shoot you an e-mail. I’ve got some suggestions for your blog you might be interested in hearing.
Either way, great website and I look forward to seeing it expand over
time.
connect on info@ymento.com
This post is truly a pleasant one it helps new internet users,
who are wishing in favor of blogging.
Great info. Lucky me I found your website by accident (stumbleupon).
I’ve saved as a favorite for later!
Thank you for the auspicious writeup. It in fact was a amusement account it.
Look advanced to far added agreeable from you! By the way, how could we communicate?
connect on info@ymento.com
Hello, yes this article is actually fastidious and I
have learned lot of things from it about blogging.
thanks.
Hi there, I enjoy reading all of your article. I wanted to write a little comment to support you.