Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

160
Views
How to stop page refresh when function is called - React

I am trying to call a function to fetch data from an api and display the data. However when I call this function, the page refreshes and state is reset so the page doesn't display anything.

In a child component, I have an input box and a form. OnSubmit, this form will save input to state (listOfNames) in the parent component. I concatenate as the state is an array that can be added to at any time to search for more names. Result is displayed in table

<Form onSubmit={() => props.setListOfNames(props.listOfNames.concat(localName))}>
    <InputGroup>
        <FormControl type="text" placeholder="Add Name" onChange={(e) => setLocalName(e.target.value)}/>
        <Button variant="outline-secondary" type="submit" variant="primary">Button</Button>
     </InputGroup>
</Form>

In the parent I have a UseEffect which detects a change to this state.

useEffect(() => {
    searchNames();
}, [listOfNames]);

On change, it will call a function (searchNames) to fetch data from the api. The fetch function uses the listOfNames state to search .

const searchNames = () =>{
    //e.preventDefault(); doesn't work even with 'e' as param

    fetch(API_URL, {
        method:'POST',
        headers: { "Content-Type": "application/json; charset=utf-8"},
        body: JSON.stringify(listOfNames)
    })
//... and so on

However when I call this function the whole page refreshes and the data won't display as the refresh resets listOfNames state to nothing before it can search. I want to know is it possible to pass an event to this function so I may preventDefault() or is there another solution.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

the default behavior of onSubmit is refresh page you can do event.preventDefault() to prevent default behavior like this

<Form onSubmit={(event) => {
    event.preventDefault()
    props.setListOfNames(props.listOfNames.concat(localName))
}}>
    <InputGroup>
        <FormControl type="text" placeholder="Add Name" onChange={(e) => setLocalName(e.target.value)}/>
        <Button variant="outline-secondary" type="submit" variant="primary">Button</Button>
     </InputGroup>
</Form>
about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!