Stuck on a problem with voting app

Stuck on a problem with voting app
0

#1

I’m currently working on the voting app and I’m having trouble getting the voting data back from the server in the way I want. I’m using all React to build the frontend, and for the component that handles the voting mechanism, there is a button that when you press it, it sends a form to the server containing the choice that was picked. It then goes into the database and updates the number of votes.

My issue is that with the same button press, I want to also fetch this updated data in a click handler so that I can render it in chart form, but I’m almost sure this is the incorrect way to do it. Does anyone have any ideas? Thanks in advance.


#2

You could send the required data in the response from the backend and use it on frontend (as a callback or as a promise) to update the state.


#3

Thanks for the response! I was thinking about doing this, but since I’m only posting the form data, where would I receive the response?


#4

Ahh I think I got it! Instead of posting it to the server directly from the html, I could handle everything in a handler function that way I could also receive a response in a callback.


#5

If you want to use the HTML form for sending the data, you can do the following:

Each poll page has a URL ending with ‘/poll/pollID’, for example http://myvoting.com/poll/123456. When you open this page, you can use ajax-get to grab the corresponding poll data from the server.

Then use the HTML form for posting the vote to the server, to ‘/polls/vote/:id’. Then on the server side, redirect the user back to the poll page ‘/poll/pollID’. Now, ajax-get is performed again to update the voting data for the poll. Let me know if something’s unclear.

I hope this helps.


#6

Thanks for the reply! I’m a little confused about the ID. This would mean that when I fetch the list of votes from the database, I should also include with it the database ID?


#7

Sorry, my reply comes a bit late. I hope you have already progressed with the voting app. Let me know how you solved the problem in the end.

I used the actually database ID when I was fetching the list of votes. The ID can also be a unique poll name such as ‘My favourite food’, but then you have to make sure there are no duplicates. By using the database ID, you are guaranteed to get unique IDs.

I am not experienced enough to say if it’s bad practice to send the unique database IDs to the client side.


#8

No problem! I did try using the database id’s initially, but I found a much easier way to do it without having to use a different page for the votes. I used react so what I did was create a component for the votes and pass in the data as props so I wouldn’t have to make a request to the server. Basically once I render the list, I handle it all on the frontend.