From ff43730d806faf03b488ee59c49d576686696d6c Mon Sep 17 00:00:00 2001 From: Carl Worth Date: Tue, 9 Jun 2020 19:46:28 -0700 Subject: [PATCH] Empathy: Add support for submitting answers to a prompy For this we convert ActivePrompt from a function to a class-based React component. Then we use the "uncontrolled components" technique again to arrange for an array to hold the form values. Finally, when answers are submitted successfully we display a simple, static message. Eventually, we'll want to display some dynamic updates as other players vote, (but for that, we'll also need the server to give us that information). --- empathy/empathy.jsx | 120 ++++++++++++++++++++++++++++++-------------- 1 file changed, 83 insertions(+), 37 deletions(-) diff --git a/empathy/empathy.jsx b/empathy/empathy.jsx index 0771bbe..3946189 100644 --- a/empathy/empathy.jsx +++ b/empathy/empathy.jsx @@ -291,51 +291,97 @@ const LetsPlay = React.memo(props => { ); }); -const ActivePrompt = React.memo(props => { +class ActivePrompt extends React.PureComponent { - function handle_submit(event) { + constructor(props) { + super(props); + const items = props.prompt.items; + + this.state = { + submitted: false + }; + + this.answers = [...Array(items)].map(() => React.createRef()); + this.handle_submit = this.handle_submit.bind(this); + } + + async handle_submit(event) { + const form = event.currentTarget; /* Prevent the default page-changing form-submission behavior. */ event.preventDefault(); + + const response = await fetch_post_json(`answer/${this.props.prompt.id}`, { + answers: this.answers.map(r => r.current.value) + }); + if (response.status == 200) { + const result = await response.json(); + if (! result.valid) { + add_message("danger", result.message); + return; + } + } else { + add_message("danger", "An error occurred submitting your answers"); + return; + } + + /* Everything worked. Server is happy with our answers. */ + form.reset(); + this.setState({ + submitted: true + }); } - return ( -
-

The Game of Empathy

-

- Remember, you're trying to match your answers with - what the other players submit. - Give {props.prompt.items} responses for the following prompt: -

-

{props.prompt.prompt}

-
- {Array(props.prompt.items).fill(null).map((whocares,i) => { - return ( -
- -
- ); - })} - -
- + render() { + if (this.state.submitted) + return ( +
+

Answers submitted

+

+ Please wait for the rest of the players to submit their answers. +

+ ); - -
- ); -}); + return ( +
+

The Game of Empathy

+

+ Remember, you're trying to match your answers with + what the other players submit. + Give {this.props.prompt.items} answers for the following prompt: +

+

{this.props.prompt.prompt}

+
+ {Array(this.props.prompt.items).fill(null).map((whocares,i) => { + return ( +
+ +
+ ); + })} + +
+ +
+ +
+
+ ); + } +} class Game extends React.PureComponent { constructor(props) { -- 2.43.0