Created
September 9, 2017 13:02
-
-
Save DZuz14/5f83a3622984cb79eda4240c55ca0085 to your computer and use it in GitHub Desktop.
Survey Component
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class Survey extends React.Component { | |
constructor(props) { | |
super(props) | |
this.state = { | |
questions: [], | |
voteCount: {} | |
} | |
} | |
/** | |
* Grabs questions via AJAX and sets them to an array in state | |
*/ | |
componentWillMount = () => { | |
axios.get('sample-data.json') | |
.then(res => { | |
this.setState({ questions: res.data }) | |
}) | |
.then(() => this.createVoteCount()) | |
} | |
/** | |
* Create an object that will keep a running count of all of the votes. | |
* Each questions vote count is stored as a key value pair in this object | |
*/ | |
createVoteCount = () => { | |
let obj = {} // Construct empty object | |
// Loop through questions array | |
for(var i = 0; i < questions.length; i++) { | |
let newProp = parseInt(questions[i].id) | |
obj[newProp] = 0 | |
} | |
this.setState({ voteCount: obj }) // Create new object as state | |
} | |
/** | |
* Render all of the questions to the screen | |
*/ | |
renderQuestions = (question, i) => { | |
return ( | |
<SurveyRow | |
key={i} text={question.text} | |
id={question.id} | |
increment={this.incrementCount} | |
decrement={this.decrementCount} | |
count={this.state.voteCount[i]} | |
/> | |
) | |
} | |
/** | |
* Submit results to the backend. Was thinking about sending | |
* a serialized object. Not sure what the data model is yet. | |
*/ | |
submitResults = () => { | |
let votejson = JSON.stringify(this.state.voteCount) | |
} | |
render() { | |
return ( | |
<div> | |
{this.state.questions.map(this.renderQuestions)} | |
</div> | |
) | |
} | |
/** | |
* Increment and decrement button functionality. It creates a new object on the fly, | |
* so we dont mutate the object currently in state. It then sets the newly created | |
* object as the new state. | |
*/ | |
decrementCount = (id) => { | |
let check = this.state.voteCount | |
// Exit case if current value is zero. No need for negative values. | |
if(check[parseInt(id)] === 0) | |
return | |
else { | |
let newCount = this.state.voteCount // Construct copy of current object in state | |
newCount[parseInt(id)] -= 1 | |
this.setState({ voteCount: newCount}) | |
} | |
} | |
incrementCount = (id) => { | |
let newCount = this.state.voteCount // Construct copy of current object in state | |
newCount[parseInt(id)] += 1 | |
this.setState({ voteCount: newCount}) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment