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