0

I have 2 components App.js and Search.js. Search.js has an input field and a button. When a user is typing the input value it is getting set to the "searchedUser" state variable in Search.js using onChange.When I am clicking the button, I want to send the "searchedUser" to App.js, and with the help of the function "UserNamefunc" I want to set the state variable "userName" as the passed-on value.

But when I am clicking the button, the previous state is getting passed to the "UserNamefunc" from Search.js to App.js.I know setState() is async but how to update the passed value immediately to the state variable on onClick?

I tried passing value to setState() using the callback function, but that is also not working. Can someone help?

// search.js

const Search = ({UserNamefunc}) => {
  const [searchedUser, setsearchedUser] = useState();

  
  return (
    <div className="search">
      <div className="searchField">
        <input type="text" placeholder="Search Github UserName" onChange={(e)=>setsearchedUser(e.target.value)}/>
      </div>
      <div className="searchBtn">
        <button onClick={()=>UserNamefunc(searchedUser)}>Search</button>
      </div>
    </div>
  );
};


// App.js function 

const [userName, setuserName] = useState("rajat-mehra05")

  function UserNamefunc(val) {
    setuserName(() =>val)
    console.log(userName)
  }

1 Answers1

-1

Only use one state here. Also you can utilize a useRef hook to grab the input element's current input value. Ex:

// search.js

import React, { useRef } from 'react';

const Search = ({ setUserName }) => {
  const inputRef = useRef(null);
  return (
    <div className="search">
      <div className="searchField">
        <input ref={inputRef} type="text" placeholder="Search Github UserName"/>
      </div>
      <div className="searchBtn">
        <button onClick={()=> setUserName(inputRef?.current?.value)}>Search</button>
      </div>
    </div>
  );
};


// App.js function 

import React, { useEffect } from 'react';

const App = () => {
  const [userName, setUserName] = useState("rajat-mehra05");

  // You can replace this with a handleSubmit() function 
  // or whatever you'd like to do with the submitted username value.
  useEffect(() => {
    console.log(`Your most up-to-date username is ${userName}`);
  }, [userName]);

  return (
    <Search setUserName={setUserName}>
  );
}

tuckermassad
  • 126
  • 4