1

i have been trying to create a simple posting mechanism like a personal note taker. something like twitter posting. so while i am doing coding in react i get this unusual bug where i get my current state after TWO clicks. this is frustrating as i have been rereading the code for over an hour and i dont think i did anything wrong. some posts suggest using useffect because usestate is asychronous and will not update the state immediatly . how do i fix this i have attached my code below.

function Poster() {
    const tw = useRef('')
    const [post,setPost] = useState([])
    
    function PostNow(event){
        
        
        setPost((oldpost) => [tw.current.value,...oldpost]);
        
        return console.log(post)
        
        
    }
  return (
    
    <div >
        <textarea ref={tw} ></textarea>
        <button className="postIt" onClick={PostNow}>press me</button>
    </div>
    
  )
}

export default Poster
  • it's not a bug it's just how react works. you don't need state value in the next lines you set that state – abolfazl shamsollahi Nov 09 '22 at 11:20
  • so , when you are logging post for the first time , it's value is '[]' only , once the state is set , i.e using setState() , it will cause the re-render , only then you can log the state value. Moreover , if you want to log the textarea value , log tw.current.value – Sarthak Gupta Nov 09 '22 at 11:25
  • Why is the `post` an array? should it contain multiple posts? – user20386762 Nov 09 '22 at 11:32
  • the array is there so i can store the value of posts and then edit them in every rerender – Techlover69 Nov 09 '22 at 13:11

0 Answers0