-1
const [inputValue,setInputValue] = useState("")
handleChange = (e)=>{
 setInputValue(e.target.value)
console.log(e.target.value,inputValue)
}

this is a simple input tag onChange function but the thing here inside the handleChange function when am logging the values e.target.value is what am typing on the field and inputValue which is the state am setting is actually empty so if i type let's say 'd' in the input field the value of the state is actualy empty and the next time i type something now it has the value 'd' which i have typed on previously...pls help me solve this

jkv27100
  • 11
  • 3

2 Answers2

1

Yes. State change is async operation. console.log immediately executed. That mean console.log print the inputValue before the state update. That why if doing second its showing previous value.

Better you can detect the state change using useEffect

useEffect(()=>{
  console.log(inputValue)
},[inputValue])
prasanth
  • 22,145
  • 4
  • 29
  • 53
  • But this will render dom many times –  May 24 '22 at 06:27
  • 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 – jkv27100 May 24 '22 at 06:30
  • @mohitmaroliya all that effect does is run some code if the `inputValue` changes. It doesn't change state (although it could), and so there would be no re-rendering. – Andy May 24 '22 at 06:47
0

"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>
Andy
  • 61,948
  • 13
  • 68
  • 95