"the thing is that i want to do a search bar and because of this when i type let's say "a" or something search doesn't work because the state value is empty that time."
Setting state is an async process. When you try to log the state immediately after setting it all you're doing is logging the existing state before the component has re-rendered.
@prasanth is correct with their answer that adding a useEffect
to watch for changes in the input state is the only way to log that new state.
If you're trying to write a search bar here's a quick contrived solution that filters out animal names from an array.
const { useState } = React;
function Example({ data }) {
// Initialise the input state
const [ input, setInput ] = useState('');
// When the input value changes
// update the state
function handleChange(e) {
setInput(e.target.value);
}
// `filter` the data using the input state,
// and then `map` over that array to return
// an array of JSX
function getFiltered(input) {
return data
.filter(el => el.toLowerCase().includes(input))
.map(el => <p>{el}</p>);
}
return (
<div>
<input
type="text"
placeholder="Find an animal"
onChange={handleChange}
value={input}
/>
<div>{getFiltered(input)}</div>
</div>
);
}
const data=["Alpine Goat","Beaver","Carolina Parakeet","Dragonfish","Eurasian Wolf","Frilled Lizard","Gila Monster","Honduran White Bat","Immortal Jellyfish","Japanese Macaque","Kooikerhondje","Leopard Gecko","Megalodon","Nova Scotia Duck Tolling Retriever","Orb Weaver","Pink Fairy Armadillo","Rhombic Egg-Eater Snake","Satanic leaf-tailed gecko","Tibetan Fox","Umbrellabird","Vervet Monkey","Whoodle","Xoloitzcuintli","Yeti Crab","Zonkey"];
ReactDOM.render(
<Example data={data} />,
document.getElementById('react')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/17.0.2/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/17.0.2/umd/react-dom.production.min.js"></script>
<div id="react"></div>