Search code examples
reactjsinputlocal-storagestatestore

ReactJs retains multiple react values and do not reset state after being refreshed


in the codesandbox link here i have a form with multiple inputs, i want to store the input value into localstorage of each one and everytime i refresh the page, the value of each one still there and of course, when it on change, the localstorage automatically update the value of each one as well, thank for help me out and have a good day, thank you :)

p/s: as you can see in this gif image gif,

i can store their values in the localstorage but i dont know how to retain the value on the input when page is refreshed and update it as well. my idea is to clone Medium and when user want to write new story, it automatically generate a new id in the url params, when input text onChange, the firebase realtime database will store event.target.value and keep it in the localstorage as well but when i refresh the page, the state of the text is gone and i dont know how to handle it, thank for taking time to help me, i really appreciate that


Solution

  • I hope this answers your query, the reason why you may not be able to set the prefilled values the input on reload because the input elements are not controlled input. In browser environment, there can be two types of inputs and actions for users controlled and uncontrolled, the input is controlled when you pass it a value attribute and tell it what shall be the value for it,

    Whereas for an uncontrolled input will not require the value as an attribute. Whenever the user will enter a value the value will be reflected in the UI because the HTML input element will store it in its local state for visual feedback to the user.

    The concept of controlled and uncontrolled inputs comes really handy in case when you are fetching some data via an API and then you have to auto-fill the inputs with some previously filled data from API. That time also you will need the input to be a controlled input. In your scenario the instead of API it in localStorage. I have updated your code sandbox link with my code. Please review it and share it if it does not work.

    https://codesandbox.io/s/react-multiple-input-value-demo-forked-tf423?file=/src/Demo.js

    Please find some of the reference links related to controlled and uncontrolled inputs:

    https://goshakkk.name/controlled-vs-uncontrolled-inputs-react/

    https://reactjs.org/docs/uncontrolled-components.html

    https://www.robinwieruch.de/react-controlled-components