Home > Enterprise >  Problem with changing values of State Hook which is an object
Problem with changing values of State Hook which is an object

Time:01-04

I have rather simple problem.

I don't know why my useState function won't change state -> props

onChangeText={(text) => {
        setProps({ ...props, inputValue: text });
      }}

I declared my state as here:

const [props, setProps] = useState({
    pageNumber: 2,
    inputValue: "",
  });

Thanks in advance!

CodePudding user response:

prevState received by the updater function are guaranteed to be up-to-dateis. It's a reference to the component state at the time the change is being applied. Official docs

onChange={(event) => {
    setProps(prevState => {
       return { ...prevState, inputValue: event.target.value }
    });
}}

Also if you have input just use native event onChange instead of custom onChangeText

CodePudding user response:

You wrote 'onChangeText' instead of 'onChange'. And, it gives you the event object rather than the text itself. It should be like this:

    <input onChange={(event) => {
        setProps({ ...props, inputValue: event.target.value });
      }} />

CodePudding user response:

What you doing is correct and nothing is wrong with it.

you need to pass your state value to the input

import { useState } from "react";

export default function App() {
  const initialState = {
    pageNumber: 2,
    inputValue: ""
  };

  const [props, setProps] = useState(initialState);

  const textInputChangeHandler = (e) => {
    setProps({ ...props, inputValue: e.target.value });
  };

  return (
    <div className="App">
      <input
        value={props.inputValue}
        type="text"
        onChange={textInputChangeHandler}
      />
    </div>
  );
}
  • Related