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