tomen
tomen

Reputation: 539

ReactJS - Can not return jsx for callback function?

I have been working with react for a while but I got to very basic problem but I don't understand why it doesn't work. Basically, in Login component I submit a form and when it return an error, render a snackbar message.

  handleSubmit = (event) => {
    event.preventDefault()
  //api call here
    onFormSubmit(this.state)
     .then(() => history.push('/teams'))
     .catch(e => <Snackbar message={e}/>)
  }

  render() {

Console shows no errors but I don't see any snackbar when the onFormSubmit call fails.

Update

I understand now, I didn't place Snackbar inside render () { return (.... I can think of the only way to do it like that:

this.state = {
  email: '',
  password: '',
  error: ''
}
handleSubmit = (event) => {
event.preventDefault()
//api call here
onFormSubmit(this.state)
 .then(() => history.push('/teams'))
 .catch(e => this.setState({error: e})
}
render () {
 return (
   <div>
      {this.state.error && <Snackbar message={this.state.error}/>}....

But I don't want to submit also the error field to server. Is there another way to inject it to component?

Upvotes: 1

Views: 913

Answers (2)

Olivier Boiss&#233;
Olivier Boiss&#233;

Reputation: 18143

your solution is correct, you can also delegate the handleSubmit to the parent component, then if you have an error you display the Snackbar component otherwise you display the Form component.

In your example, if you don't want to post the error, you can destructure the state object to control the properties you want to send.

handleSubmit = (event) => {
  const {email, password} = this.state;
  event.preventDefault()
  //api call here

  onFormSubmit({email, password})
    .then(() => history.push('/teams'))
    .catch(e => this.setState({error: e})
}

Upvotes: 2

Christian Asivido
Christian Asivido

Reputation: 51

You will need to place that component into rendered JSX, or inject it somehow. Are you calling handleSubmit inside of your render's return?

One option is to use JQuery inside of that catch to inject that Snackbar onto the page.

A better option is to somehow trigger that component inside of your render's return like normal. For instance, set a localState variable of error to true inside of the catch, and then render the snackbar conditionally inside of your render based off this.state.error being true.

Upvotes: 1

Related Questions