I'm making a trivia game where the data is on MYSQL. My code for calculating the score is functioning properly. However, how do I get this score to be posted through REST API? I have this as my handleScore for when the user submits the game to calculate their score.
const handleScore = () => {
let s = 0
for(let i = 0; i < questions.length; i ){
if(questions[i].answer == myAnswers[i]){
s
}
}
setScore(((s*10)/questions.length)*10)
}
I have this to fetch and POST:
const addScore = () => {
const init = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${auth.user.token}`
},
body: JSON.stringify(score)
};
fetch(`http://localhost:8080/api/score/${scoreId}`, init)
.then(response => {
if (response.status === 201 || response.status === 400) {
return response.json();
} else {
return Promise.reject(`Unexpected status code: ${response.status}`);
}
})
.then(data => {
if (data.scoreId) {
history.push({pathname: `/score/${scoreId}`, state: { scoreId: scoreId }});
} else {
setErrors(data);
}
})
.catch(console.log);
};
Would I need to combine these two in order to save the score? Right now, there is a button for finishing the game and it only has "handleScore" as the onClick.
Submit button:
<button onClick= {handleScore}>Submit</button>
My question is, would I need to combine the following code I wrote above? Or, would I need to have my onClick to have 2 functions with 1 function to save the score to MYSQL and the other function to calculate for the user to view the score?
CodePudding user response:
ideally each function should have own responsibility, in my opinion the best variant here is to use this 2 functions in such way:
const handleScore = () => {
let s = 0
for(let i = 0; i < questions.length; i ){
if(questions[i].answer == myAnswers[i]){
s
}
}
return ((s*10)/questions.length)*10
}
const addScore = (score) => {
const init = {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': `Bearer ${auth.user.token}`
},
body: JSON.stringify(score)
};
fetch(`http://localhost:8080/api/score/${scoreId}`, init)
.then(response => {
if (response.status === 201 || response.status === 400) {
return response.json();
} else {
return Promise.reject(`Unexpected status code: ${response.status}`);
}
})
.then(data => {
if (data.scoreId) {
history.push({pathname: `/score/${scoreId}`, state: { scoreId: scoreId }});
} else {
setErrors(data);
}
})
.catch(console.log);
};
const handleSubmit = () => {
const scoreResult = handleScore(); // responsoble only for calculating score
setScore(scoreResult) // not required, but you can write, if you need latest score somewhere else to use
addScore(scoreResult) // responsoble backend and pushing to next route
}
<button onClick={handleSubmit}>Submit</button>