Home > Blockchain >  get current useState values inside functions (w/ short, explicit codepen)
get current useState values inside functions (w/ short, explicit codepen)

Time:07-06

I understand (somewhat) how to use useEffect to update state, but I struggle with situations like when you need current state inside of another function, before the "nextTick" as it were.

Here is a simple Codepen with the exact issue. Make sure the Pen console is open.

https://codepen.io/kirkbross/pen/vYRNpqG?editors=1111

const App = () => {
  const [state, setState] = React.useState(null);

  // how can I make sure the below function knows what the current state really is?
  const handleAppend = (state) => {
    console.log("click");
    console.log(state?.text   " foobar");
  };

  return (
    <div >
      <div className="row">
        <span>Text: </span>
        <input
          type="text"
          onChange={() => setState({ text: e.target.value })}
        />
      </div>
      <div className="row">
        <button onClick={handleAppend}>
          Append "foobar" to text and log it to console
        </button>
      </div>
    </div>
  );
};

CodePudding user response:

You're shadowing your state variable in your handleAppend function. You don't need to pass in an argument since state is available in scope of the component

  const handleAppend = () => {
    console.log("click");
    console.log(state?.text   " foobar");
  };

CodePudding user response:

I did some changes. You dont need to use ur state as a parameter, since your textState lives inside your app component and there for you can reach it within your function.

Also, i changed the state and setState to textState, setTextState to make it less confusing. Also after clicking on the button and console logging, i cleared the textState so the next value wont be effected. Check it out below.

function App() {
  const [textState, setTextState] = React.useState(null);

  const handleAppend = () => {
    console.log("click");
    console.log(textState    " foobar");
    setTextState('')
    //also, you could make the input box clear after each press on button by adding value={textState} in the input.
  };

  return (
    <div className="App">
      <input
          type="text"
          onChange={(e) => setTextState(e.target.value)}
        />

<button onClick={handleAppend}>
          Append "foobar" to text and log it to console
        </button>

    </div>
  );
}
  • Related