Answer the question
In order to leave comments, you need to log in
How to store a variable in the database in React?
I want to implement likes and number of views on the site. Clicks work for me through react.
The problem is that I still don’t understand what the aggregation of actions should be in order for them to be remembered. Now I stupidly increase with each click, and when I reload the page, the score is reset to zero.
I’ll say right away that I’m not friends with the back-end, I know just a little PHP and mysql.
Here's what I think, correct me if it's wrong:
1) using ajax, I take the changed this.state.like and pass it to the php page.
2) with the help of localStorage I make a restriction so that it would be possible to increase the counter only once for one user.
3) Somehow, using queries, I transfer data to mysql,
4) This data from the table should somehow end up in react in this.state.like
Am I thinking right?? Thank you!
Answer the question
In order to leave comments, you need to log in
LocalStorage - individual storage.
You need a shared storage - a database (MongoDb, MySql...)
Of course you can query the shared storage if you have a special library that gives an API to it.
But this is not recommended, as anyone can modify requests, etc.
Either way, you need a server to display the page, most likely in your case webpack is configured or you use create-react-app and don't notice it.
Ideally, everything should be like this:
1) Take the number of views from the database, and change the state.
2) When a person clicks, make an ajax request to the server so that it uploads a value to the database.
In componentDidMount () you need to put a function that will take data from the database and display it. By the key, you need to increase the value in the database and call a function that will again take new data from the database. This way you don't need LocalStorage at all
Here it is necessary to implement exactly without localStorage! Otherwise, it will be filled with all the likes that were previously.
The algorithm of actions for your case:
1 a click is made on the like
2 An http request is sent to the server
3 The request is processed by the server and if everything is fine, it increases the likes in the database and returns "success"
4 React, having received the server's approval, increases the like by 1
This is a simple way to increase the like
If you need a complicated one, then at the end, instead of increasing the number by 1, another request is made, which is equal to the new number of likes and the new number is already displayed. This will make it possible to show the actual number of likes. For example, if after loading the page and liking the post, 10 more people managed to like it, then the number of likes will immediately grow by 10 + 1 your
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question