简体   繁体   中英

I am trying to stop my browser from refreshing when making a Post request to the backend in my handleSubmit function

I have a form with a handleClick on my submit button. In my handleSubmit function I am making a Post request to the backend and it is sending the data to the backend and updating state. However, it is refreshing the whole page when doing so.

How can I prevent it from refreshing the browser?

I've tried e.preventDefault(); this only forces you to hit the refresh to see it rendered in the browser.

handleSubmit = async (e) => {
 console.log(e);
 const data = this.state.list;
 try {
   const addItem = await fetch('http://localhost:9000/addItem', {
     method: 'POST',
     credentials: 'include',
     body: JSON.stringify(this.state),
     headers: {
       'Content-Type': 'application/json'
     }
   });
 } catch(err) {
   console.log(err);
  }
}


componentDidMount() {
  this.getList().then((list) => {
   this.setState({list: list.data})
  }).catch((err) => {
   console.log(err);
  })
}
render() {
 let data = this.state.list
 let categoryList = Object.keys(data).splice(0, 9).map((item) =>
       <div className='category' key={item}>
         <h1> {item} </h1>
         <div className='itemWraper'>
           {data[item].map((value) =>
             <div key={value} style={{display: 'flex'}}>
               <p className='item'> {value} </p>
               <button className='deleteButton' item={value} id= 
                {this.state._id} onClick={() => this.deleteItem(value, 
                this.state._id, item)}>X</button>
             </div>
           )}
         </div>
       </div>
     )
 let category = Object.keys(data).splice(0, 9).map((item) =>
   <option key={item} value={item}>{item}</option>
 )

 return(
   <div className='background'>
       <h1 className='listName'> {this.props.data.name} </h1>
       <div className='wrapper'>
           <form>
             <input className='addItemInput' type='text' name='name' 
             placeholder='your item..' onChange={this.handleChange}/>
            <div className="select">
             <select name='category' onChange={this.handleChange}>
               <option> Choose a category </option>
                 {category}
             </select>
            </div>
            <button onClick={this.handleSubmit} 
            className='addItemButton'> + </button>
          </form>
       </div>
       <div className='categoryWrapper'>
           {categoryList}
       </div>
   </div>
  )
 }
}

No errors. It's working functionally. I would just like it to be more react like

I guess that you're using a submit button like If this is the case, then clicking on that button refreshes the page. So, changing type from submit to button may solve your problem.

e.preventDefault() is gonna be necessary for keeping the page from reloading.

You should add the item to your components state or apps state at the same time as you post it so it still displays.

handleSubmit = async (e) => {
 console.log(e);
 const data = this.state.list;
 try {
   const addItem = await fetch('http://localhost:9000/addItem', {
     method: 'POST',
     credentials: 'include',
     body: JSON.stringify(this.state),
     headers: {
       'Content-Type': 'application/json'
     }
   });
   this.setState({list: [...this.state.list, YOUR_NEW_ADDITION_TO_THE_LIST]})
 } catch(err) {
   console.log(err);
  }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM