I'm having trouble sending button text value back to the server.
The code of the button in client-side:
{question.options?.map((option, index) =>
<button key={index} className={styles.answer} onClick={() => guessHandling()}>{option}</button>)}
The code of the onClick guessHandling function in client-side:
const guessHandling = async (userGuess) => {
const res = await axios.post('/api/guess', { userGuess });
setStatusMessage(res.data.returnStatus);
};
The code in server-side:
app.post('/guess', (req, res) => {
console.log(req.body.userGuess); // <---- I RECIEVE "UNDEFINED" IN THE SERVER CONSOLE HERE.
res.send({
returnStatus: "Guess Recieved"
});
});
userGuess is undefined when I try to console.log it as seen above.
I also tried including .value, .innerText, .innerHTML... still does not work.
I tried using useState, but I do not know how to insert the button text into the state (which is the main problem of this question).
(Probably?) I'm missing something in the onClick functionality.. I would love to get some help on this problem.
As Elan Hamburger wrote in the comments, Solution is simple:
You didn't actually pass the value into your call to guessHandling. Try: onClick={() => guessHandling(option)}