Extra GET API call after update call - javascript

As the frontend application has its own state, now the user updated his/her contact and the frontend state got updated and PUT API is called to update with the current state.
So while updating the user contact details through PUT call, should another GET call be made to fetch the user details or should the current state is enough for the frontend.
Just curious what is the advised pattern to follow.

Your PUTrequest should send a 200 ok so you know that the data frontside is now valid.
You could of course (this is what I do in some instances), is send the object back as a response of your PUT request with a 200 ok. With this object you can update your view as needed, ensuring that the object is exactly the same as the one on the server side.
A GET is not needed in this case.

Another get request is not necessary, If you really want to maintain the state from backend (which is also not necessary), you can respond from the server to the PUT Request with the state. This may come in handy if to know execution is successful.

After update(PUT call) you should make GET call to get the details from DB and display in the front end.
So that the user will get to know that the details are successfully updated.
OR
if you want to show update success message then in the backend you can return the updated values in PUT API call response and you can use this response to show details without making GET API call again.
OR else
Based on PUT call success response you can show the details that you set in the state without making a GET call

Not required.However,in the PUT request itself you can send the changed state.And you can concatenate/update the frontend state with the db state using filter method.In order to keep your frontend state intact with the db.

Related

How to do background sync instead of fetch requests on UI changes?

For example, let's take a simple web application with comments feature. In my understanding, when a user posts a new comment, the following would occur:
display UI loader;
update the front-end state;
send a fetch request to the API to post a new comment;
Wait for the response;
send another fetch request to the API to request the new list of comments;
waiting;
update the front-end state with new comments;
update UI to reflect the new state with a new comment;
And the user needs to wait while front-end app interacts with back-end on almost every data change. The same way we did it earlier with PHP/Python/Ruby, ajax, server-side rendering and templates.
That makes me think what's the point of adding so much front-end complexity with something like react, when the result is basically the same.
My question is: are there any alternative approaches to this? Is it possible instead to do the above case the following way:
user clicks to post a comment;
update the front-end state;
update UI to reflect the new state with a new comment;
sync front-end state with API DB in the background;
Well, as your question is tagged react, you could use the Apollo library (it is intended to work together with graphql on the backend) for data fetching. It offers a feature called Optimistic UI, which will be update the frontend with the respected result, until it receives an answer from the backend. If the expected result differs from the received one, the component will change the UI automatically to the real result. In case of an error, it will show an error message.
You definitely could, your first method is just way of doing it.
Apart from 'syncing' your front-end state, another method is also to just pre-emptively update the UI (step 7 & 8 in your first method) before doing step 3-6, and only reverse the action if the API call failed. This should allow for slightly better UX for the end-user too.
I get it that you think it's waste of time for users to wait until requests are successful. However, isn't it more important to stop users from keeping making bad requests to the server?
So, what I would do is just to stop fetching data from the database every after users make requests.
Fetching the DB data to begin with and store them in redux states
Make requests to the DB while holding users from doing anything
Make changes to the redux state if the requests are successful
But what you want to do could be done like this
Fetching the DB data to begin with and store them in redux states
Make changes to the redux state while making requests to the DB in the background
Depending on whether the requests fail or not, roll back the change users made from the redux state

react send a request to server on constructor for set list

in react I want to send a sync instead of async ajax request to the server for getting category list on constructor because if the server is busy, the response will be late that means the page will be rendered without category list.
I think it is a good idea that creates/edit a JSON file after every category event but I want to learn the right way.
how can I do it or what is the right way to it?
I would set an empty array in the state in the constructor. And in componentDidMount I would start an async request. When it returns it updates the state and you get your category list.
You can set a loading state as well. Set true at the start of ajax request and set false as you get back the result.
Use the loading state with conditional rendering to display a loading indicator.

Vue js and favorite/like button

I'm wondering how favorite, subscribe or like buttons work.
I don't understand something.
For exemple:
A user like a post with id 243.
A ajax request is sent to the server with the id of the post (243) [here comes back end stuff, the user's favorite list is updated, including that post] and the server sends back a success response.
Now, how I suppose to deal with modifying the like button to actually display that is liked (permanently, including refresh).
How can I achieve that in Vue JS. How things get updated? I don't understand this part.
If the server sends back a successful response you can increment the number that is already there.
This initial number is something you have gotten either through a prop, directly from the server or through an initial AJAX request.
If you want to "permanently" update the amount of likes on your button you have to persist it to a database(or some other storage medium). On you server you could have a route that accepts a post id as an argument and increment that specific user post:
/incrementlike/243
That is where you would make a POST ajax request to. Most of the time in an MVC framework you would have a controller action/method mapped to this route that holds the logic to respond to this call.
If you are interested in the part that happens after you make an AJAX request to the server to increment your like on the backend side, I suggest you read up on routing or MVC structure.
How you would do this is really done on a case by case basis. It really depends on a number of things, for example what your backend does to a post when it is liked.
If you would like a general 'explanation' to the process I attach it below, this is not really Vue specific, but the general idea is the same:
Frontend side:
Modify the local state of you post to set the proper flag, ex. post1.liked = true immediately when it is clicked, before sending the request to the server.
Make sure your GUI represent this change. ex. Base the color of the button on the property 'liked' of each post.
If a failure response it received from the server, notify the user and allow them to 'try again' or something similar.
When refreshing the page, make sure changes are fetched from the server, If you have done the backend part correctly, the modification of the state of the post will be correct in the data you receive from your backend (post1.liked will be true)
Backend side
When the request comes in, modify the state of the post the correct way and make sure that next time the post is fetched, the new state is sent.

Retaining a value from a response in node js

On page load, say for a particular route for (e.g. https://localhost:8000/home/index), a service is called and the response from the service is rendered to the page at the client side.
On the same page, I have a link that pops up a Backbone.js modal and from the modal a click event triggers which hits another url (e.g. https://localhost:8000/home/index2) upon which another service call triggers and the response is rendered to another html page.
On the same html page, I want to display a value which I got from the first service call on page load. However, I am unable to retain that value as there are two different requests each time. Hence, I cannot even append the value from first response to the request object and use it a second time.
You can use JavaScripts Web Storage API to storage information on client browser.
MDN Web Storage API
For example, If you are on the first screen and call a service, store the service information on localStorage
localStorage.setItem('firstService', serviceResponseObject);
Once you are navigated to second page, you can use localStorage to read to previous service information
localStorage.getItem('firstService');
There are multiple ways to store state between requests.
From the server, if you're using say Express etc, you could store the result in a Session. Or you can even store state in the requests query params, or from a POST request.
You could also store some data on the client end, using say Cookies or localstorage.
What you choose really depends, it might be best if you explain in more detail what sort of information your passing between pages.
If it's just a simple value, I would go for using query params.
eg. Just place in your url https://localhost:8000/home/index2?value=123, and then from node.js, req.query.value would have your value.

Using Different Objects In Array Model AngularJS

I am very new to angular and this one is striking in my head a lot. So scenario is : Suppose angular http returns me model containing array of object like:
[{name:"Ankur",lastName:"aggarwal",updation_date:"23-08-2014"},{name:"xyz",lastName:"abc",updation_date:"29-08-2013"}]
Out of this updation_date is not required but coming for some reason. So is it right to update the array with third object without creation date like {name:"def",lastName:"jbc"} . Is it a good practice or array object model should be consistent?
Also what should be the approach? Update the model array first so binding take place instantly, then send it to the server or send it to server and get the updated object? Might be basic one but very new to angular and JMVC.
Is it a good practice or array object model should be consistent?
It depends , if backend expects all array entries to contain updation_date then you have no choice and are forced to add some sensible default value. However, if possible then avoid sending too much unnecessary data from backend since it impacts application performance(like data transfer, adding unnecessary logic to generate sensible default values, etc.)
Update the model array first so binding take place instantly, then
send it to the server or send it to server and get the updated object?
If the nature of your application permits reverting model value when save is unsuccessful then just go ahead with
0.Perform data validation, and make sure valid data is supplied to the backend.
1.Update model.
2.Send data to backend
3.If something bad happens then execute error handling depending on app needs
However if presenting consistent value in the GUI is uttermost importance(e.g. finance applications) then
0.Perform data validation, and make sure valid data is supplied to the backend.
1.Show some message to user like "saving"
2.Perform ajax request
3.If successful, update model, else execute error handling depending on app needs
It depend on your error handling.
As saving on the server-side might be not successful, you should take it into consideration.
My approach is to
Update angular object immediately
Then send AJAX request to server and
Wait for response. If error happen during server save, you shoulde:
revert values,
repeat AJAX
show information to user.

Categories

Resources