Skip to content

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.

Answer

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>