Sweetalert state problem


(Saša Fišter) #1

I have this code and

handleUpdate(e) {
    e.preventDefault()
    helpers.updateCourse(this.state).then(response => {
      this.setState({show: true})
      <SweetAlert
        show={this.state.show}
        title="Demo"
        text="SweetAlert in React"
        onConfirm={() => this.setState({ show: false })}
      />
    })
  }

I get this error

Syntax Error: Unexpected token, expected , (32:18)

30 |       this.setState({show: true})
31 |       <SweetAlert
32 |         show={this.state.show}
   |                   ^
33 |         title="Demo"
34 |         text="SweetAlert in React"
35 |         onConfirm={() => this.setState({ show: false })}

(haxxxton) #2

Using {} inside an anonymous return function implys you wish to optionally return a result, you dont appear to be doing that.

In this case, it appears you’re wanting to render a SweetAlert Component. Im not sure what your updateCourse function does, but it’s unlikely to change a render methods output, so instead of trying to return JSX from the callback function, i would instead suggest updating your render method to optionally display the SweetAlert component. Have a go with something like this:

handleUpdate(e) {
	e.preventDefault()
	helpers.updateCourse(this.state).then(response => {
		this.setState({show: true});
	})
}
render() {
	const { show } = this.state;
	return (
		<div>
			{ /* the rest of your render method */ }
			{
				show ? (
					<SweetAlert
						show={ show }
						title="Demo"
						text="SweetAlert in React"
						onConfirm={() => this.setState({ show: false })}
					/>
				) : null
			}
		</div>
	);
}

However, it does appear that SweetAlert handles its own rendering optionality through its show prop. So alternatively you could just place it directly into the render method without the need for the ternary operator.

render() {
	const { show } = this.state;
	return (
		<div>
			{ /* the rest of your render method */ }
			<SweetAlert
				show={ show }
				title="Demo"
				text="SweetAlert in React"
				onConfirm={() => this.setState({ show: false })}
			/>
		</div>
	);
}

For performance though, i would recommend moving the onConfirm function out into your class too, otherwise on every render you’re passing in a new function, like this:

_handleSweetAlertOnConfirm = () => {
	this.setState({ show: false });	
}
render() {
	const { show } = this.state;
	return (
		<div>
			{ /* the rest of your render method */ }
			<SweetAlert
				show={ show }
				title="Demo"
				text="SweetAlert in React"
				onConfirm={ this._handleSweetAlertOnConfirm }
			/>
		</div>
	);
}

(Saša Fišter) #3

The minute I saw your answer I realised how stupid I am :slight_smile: thnx!