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}); } } />       
); } }

Learn React js tutorial for beginners

Related Article

law assignment help

USA The Importance of the law assignment help services for students

Navigating the academic world for pursuing Law subjects, students have to engage in a lot of reading and writing. Whether it be school or college, assignment is an integral part of study. Law is a broad subject to study that includes a lot of…
environmental law assignment help

Get great academic grades with the help of environmental assignment services.

Environmental law involves preparing tasks based on a set of rules, regulations, and laws that govern human interaction with the environment. These laws protect the environment from human activities by relying on certain fundamental concepts.…
HUMAN RESOURCE CONSULTANT

How to Make An Essay Lengthy For Better Assignment Help Online

Maybe you wish to understand how to make a paper lengthy because you've been researching and composing the essay without accomplishing the word or page count your instructor requires. Maybe you're becoming forlorn because you might not get this…
Law Assignment Help

Assignment Law: Everything You Need to Know

Introduction Assignments are an integral part of studying law. They help students develop critical thinking skills, analyze legal principles, and apply them to practical scenarios. However, assignments can be complex and challenging,…
Constitutional Law Assignment Help

Why is it so harder to understand constitutional law papers?

, ,
The Constitutional Law Assignment Help Experts at outline Constitutional Law as a hard and fast of regulations and rules that spell out the Powers and duties of various our bodies inside a rustic country. Constitutional Law additionally defines…
lawyer-cost
cm-feet-inches
what-should-i-do-copying-my-driving-records
how-to-do-research-studies
thesis printing and binding online
Importance of personality development in a student's life
headhunting_how-to-be
HUMAN RESOURCE CONSULTANT
54 replies
  1. Tomasz Michalowski
    Tomasz Michalowski says:

    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 !

    Reply
  2. xmc.pl News
    xmc.pl News says:

    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.

    Reply
  3. Pianino.XMC.pl
    Pianino.XMC.pl says:

    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.

    Reply
  4. Socjologia.XMC.PL
    Socjologia.XMC.PL says:

    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.

    Reply
  5. Japonia Szkolnictwo
    Japonia Szkolnictwo says:

    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

    Reply
  6. Hipoglikemia Znaczenie
    Hipoglikemia Znaczenie says:

    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!

    Reply
  7. World Listings
    World Listings says:

    Really appreciate this post. It’s hard to sort the good from the bad sometimes, but I think you’ve nailed it!

    Reply
  8. Ekonomia Definicja
    Ekonomia Definicja says:

    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.

    Reply
  9. Ted
    Ted says:

    Greetings! Very helpful advice in this particular article!
    It’s the little changes that produce the largest changes.
    Thanks for sharing!

    Reply
  10. Vincent
    Vincent says:

    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.

    Reply
  11. Wiertarki
    Wiertarki says:

    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.

    Reply
  12. jasa backlink pbn
    jasa backlink pbn says:

    І 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.

    Reply
  13. Madonna
    Madonna says:

    Hello it’s me, I am also visiting this website regularly,
    this site is actually pleasant and the visitors are really sharing fastidious thoughts.

    Reply
  14. Don
    Don says:

    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!!

    Reply
  15. Rickey
    Rickey says:

    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!

    Reply
  16. Tessa
    Tessa says:

    Hi there, everything is going well here and ofcourse every one is sharing information, that’s truly good,
    keep up writing.

    Reply
  17. Krystal
    Krystal says:

    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!

    Reply
  18. Ekonomia
    Ekonomia says:

    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?

    Reply
  19. Charli
    Charli says:

    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.

    Reply
  20. Amparo
    Amparo says:

    It’s nearly impossible to find experienced people on this topic,
    but you sound like you know what you’re talking about!

    Thanks

    Reply
  21. Shayla
    Shayla says:

    Greetings! Very helpful advice within this post! It is the
    little changes that make the largest changes. Many thanks for sharing!

    Reply
  22. Shavonne
    Shavonne says:

    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!

    Reply
  23. Elsie
    Elsie says:

    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?

    Reply
  24. ps4 games and
    ps4 games and says:

    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!

    Reply
  25. on ps4 games
    on ps4 games says:

    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.

    Reply
  26. ps4 games or
    ps4 games or says:

    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.

    Reply
  27. Myrtle
    Myrtle says:

    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 =)

    Reply
  28. Lukas
    Lukas says:

    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.

    Reply
  29. Velva
    Velva says:

    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

    Reply
  30. Antoine
    Antoine says:

    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!

    Reply
  31. USA NAFTA
    USA NAFTA says:

    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,

    Reply
  32. Norris
    Norris says:

    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!

    Reply
  33. Lora
    Lora says:

    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!

    Reply
  34. Georgia
    Georgia says:

    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.

    Reply
  35. Lowell
    Lowell says:

    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?

    Reply

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

Your email address will not be published. Required fields are marked *