skip to Main Content

When i select value it always return previous value. Not returning which i selected.
I want, when i select value it quickly reflect and store current value.

const [postsPerPage, setPostsPerPage] = useState(15);

const handleChange = async (event) => {
    let data = (document.getElementById("dropzonee")).value
   
    setPostsPerPage(data)
    console.log(postsPerPage)

}


           <span>Rows Per Page</span>
            <select id="dropzonee"
                name="changedValue"
                onChange={handleChange}
                value={postsPerPage}
             >
                <option value="5">5</option>
                <option value="10">10</option>
                <option value="15">15</option>
            </select>

2

Answers


  1. Instead of

    let data = (document.getElementById("dropzonee")).value,

    try

    let data = event.target.value.

    It will always show selected value. But even so, console.log(postsPerPage) will always log previous value, because setState function works asynchronously, and it that moment state didn’t really updated. Just log event.target.value to ensure

    Login or Signup to reply.
  2. Just use event.target.value

    const [postsPerPage, setPostsPerPage] = useState(15);
    
    const handleChange = async (event) => {
        setPostsPerPage(event.target.value)
        console.log(postsPerPage)
    }
    

    or if you don’t use asyns/await, use like this

    const [postsPerPage, setPostsPerPage] = useState(15);
    
               <span>Rows Per Page</span>
                <select id="dropzonee"
                    name="changedValue"
                    onChange={(e) => setPostsPerPage(e.target.value)}
                    value={postsPerPage}
                 >
                    <option value="5">5</option>
                    <option value="10">10</option>
                    <option value="15">15</option>
                </select>
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search