-1

I am trying to set the state of my React component but the screen refreshes after the setState method is called and the value is back to default. What is going on?

Here is the code:

import React, { useEffect, useState } from "react"; import "./styles.css"; export default function App() { const friends = [ { name: "A", age: 5 }, { name: "B", age: 10 }, { name: "C", age: 20 } ]; friends.push({ name: "D", age: 30 }); const [state, setState] = useState({ ...friends[0] }); useEffect(() => { console.log(state) }, [state]); function changeState(e) { if (e.key === "Enter") { const num = e.target.value; setState({ ...friends[num] }); } } return ( <div className="App"> <form> <h1>Hello</h1> <input type="text" onKeyPress={changeState} /> </form> <div> <b>{state.name}</b> </div> <div> <b>{state.age}</b> </div> </div> ); } 

and here is a link to the sandbox:

https://codesandbox.io/s/jovial-meadow-khw5p?file=/src/App.js:0-772

7
  • This question is not about submitting forms, I am asking about why the state change doesn't take effect. What is the problem with this question? Commented Jan 30, 2021 at 5:49
  • Because you are submitting the form. Commented Jan 30, 2021 at 5:50
  • 2
    Because after you're pressing Enter, the form being submitted. And the default behavior of it is refreshing the page. And by refreshing the page, all data in your memory is gone. Your application is restarted again, the state returns to the default ones. You should preventDefault to prevent the page from refreshing. Commented Jan 30, 2021 at 5:54
  • 1
    I see... thats really good to know! Commented Jan 30, 2021 at 5:56
  • 1
    @LoiNguyenHuynh ok it works! Thx Commented Jan 30, 2021 at 6:00

1 Answer 1

1

In the code, when pressed "Enter" key changeState function is called. Browser's default submitting form action is refreshing the page and so your code restarts. To prevent this, you can call submitHandler function like below:

 function submitHandler(e) { e.preventDefault(); } 

In the code above, e.preventDefault() prevents default browser action(refreshing the page).

If you call submitHandler function at "onSubmit" attribute of the form, the refreshing page will be prevented.

return ( <div className="App"> <form onSubmit={submitHandler}> <h1>Hello</h1> <input type="text" onKeyPress={changeState} /> </form> <div> <b>{state.name}</b> </div> <div> <b>{state.age}</b> </div> </div> ); 

For more, you can check this page: MDN - Event.preventDefault()

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.