Home > OS >  is there any way to save the value of onChange?
is there any way to save the value of onChange?

Time:03-21

I'm having a question about onChange, so I was trying to pick up and send a value from my onChange to (''http://localhost:3000/search''), but when I press the (Enter) key it enters the page but ends up deleting the values of my onChange coming back undefined, is there any way to save my onChange and send to another page? without retone me undefined

My code:

function handleKeyPress(event: any) {
        if(event.keyCode === 13){
          open('http://localhost:3000/search')
        }
      }

    function search(e: any) {
    
        axios.get("http://localhost:3001/search", {params: {q: e.target.value}})
    
    }
    
    return(
        <>
            <div className={styles.Header}>

                <input name='q' type="text" placeholder='Buscar' onChange={(e)=>search(e)} onKeyDown={(e)=>handleKeyPress(e)}/>

                <div></div>
            </div>
        </>
    )

CodePudding user response:

Use setTimeout becouse the search function maybe not is loaded yet

setTimeout(open('http://localhost:3000/search'), 500)

CodePudding user response:

If you want to use window.open, this answer should help.

Otherwise, I would suggest you using react-router's useNaviage. You can pass your search param in search property, and access the param on the target page using useParams.

import { useNavigate, createSearchParams } from "react-router-dom";

...

const navigage  = useNavigate()
function handleKeyPress(event: any) {
  if(event.keyCode === 13){
    navigage(
      `${"/search"}?${createSearchParams({q: e.target.value})}`
    );
  }
}

...

in "/search" page

 let { q } = useParams();

Here how to setup react-router for your project

  • Related