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
Enter, theformbeing 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 shouldpreventDefaultto prevent the page from refreshing.