简体   繁体   中英

React useState: How can I update my useState with onChange for input and OnClick for the button?

I am trying to update the useState hook but the object is returning empty. I have tried to use something like: <input onChange={e => setFilter(name: e.target.value)} > however, it submits on each key stroke and the button is pointless, and the user cant fully complete the value (Copy and paste only works). What am I doing wrong?

export default function Search() {
  const [filter, setFilter] = useState({ name: "Hungary" });
  const { data, loading, error } = useQuery(GET_COUNTRY_INFO, {
    variables: { filter },
  });

  if (loading) {
    return <Loader />;
  }
  if (error) return <p>Error</p>;

  const userReq = {
    name: ''
  }


  function onChangeHandler (e) {
    const userReq = {name: e.target.value}
    return userReq
  };

  const onClickHandler = (e) => {
    setFilter(userReq)
  } 

  return (
    <div className="body">
      <h1>
        Get Information
        <br /> about Countries!
      </h1>
      <div className="wrapper">
          <input
            className="search"
            type="text"
            id="search"
            placeholder="Enter a Country"
            onChange={onChangeHandler}
          />

          <button className="submit" name="name" type="submit" onClick={onClickHandler}>
            Search
          </button>

        {data?.Country?.[0] && <CountryInfo country={data?.Country[0]} />}
      </div>
    </div>
  );
}

your setFilter is wrong, you are using:

setFilter(name: e.target.value)

and should be:

setFilter({ name: e.target.value });

So, the code below should work and you dont need the 'userReq' variable:

function onChangeHandler(e) {
    setFilter({ name: e.target.value });
}

const onClickHandler = (e) => {
   console.log(filter);
};

<input type="text" id="search" onChange={onChangeHandler} />

If you want onChange inline:

onChange={(e) => setFilter({ name: e.target.value })}

You probably want 2 separate states here,

  1. A state which holds the current filter

  2. A state which holds the current user's input

and on clicking the button you want to sync the user's input with the filter

Looking at your code I think you've already figured this out, so just making your userReq a state should solve your problem

Basically changing this

 const userReq = {
    name: ''
  }

  function onChangeHandler (e) {
    const userReq = {name: e.target.value}
    return userReq
  };

to this

  const [userReq, setUserReq] = useState({ name: '' })

  function onChangeHandler (e) {
    setUserReq({ name: e.target.value })
  };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM