1

I want to have a form and save the values on local storage. when I did the same thing in Welcome component without writing another component for input, I got the exact result that I wanted. but since I didn't want to write two different handleChange functions, I decided to create another component for Input. However, input's value is not saved completely on localstorage, the last letter is missing. Why does this happen?

function Welcome () {
return(
    <div className={`container ${styles.container}`}>
        <form>
            <label htmlFor="first_name"> First Name: </label>
            <br />
            <Input type="text" id="first_name" name="firstName" />
            <br />
            <label htmlFor="last_name"> Last Name: </label>
            <br />
            <Input type="text" id="last_name" name="lastName" />
            <br />
            <button type="submit" className={styles.btn}> Enter </button>
        </form>
    </div>
);

}

function Input ({name, type, id}) {
const [input, setInput] = useState("");

const handleChange = (e) => {
    setInput(e.target.value);
    localStorage.setItem(name, input);
}
return <input type={type} id={id} required onChange={handleChange} />

}

Jupixel
  • 53
  • 7
  • Actually, I deleted useState and saved the value directly on localStorage. the problem no longer exists ;) – Jupixel Feb 06 '23 at 05:39
  • 1
    That’s because setting a react state is asynchronous and it doesn’t update `input` immediately. – Terry Feb 06 '23 at 05:56
  • 1
    Does this answer your question? [The useState set method is not reflecting a change immediately](https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately) – Terry Feb 06 '23 at 05:57

0 Answers0