-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

tsm
  • 419
  • 4
  • 11
  • 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? – tsm Jan 30 '21 at 05:49
  • Because you are submitting the form. – CertainPerformance Jan 30 '21 at 05:50
  • Replace `
    ` with `
    e.preventDefault()}>` and you're good to go @Tido
    – Loi Nguyen Huynh Jan 30 '21 at 05:51
  • I am not asking how not to submit the form, I am asking why the state isn't updating... – tsm Jan 30 '21 at 05:52
  • 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. – Loi Nguyen Huynh Jan 30 '21 at 05:54
  • 1
    I see... thats really good to know! – tsm Jan 30 '21 at 05:56
  • 1
    @LoiNguyenHuynh ok it works! Thx – tsm Jan 30 '21 at 06:00

1 Answers1

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()

F.YILMAZ
  • 26
  • 3