Rerun axios.get in useEffect when url parameter changes - axios

I have been learning React Hooks recently. I have researched for a few days to know how to fetch data and realized that there was axios.
I am using it to fetch data but the problem is it is not working properly when the parameter changes in the url. I have explored tonnes of posts related to this issue here but never got proper ideas.
Here is what I have tried so far. I simplified my code in the link: MyCode.
In my code, when a checkbox value changes, the axios fetches different data.
How can I rerun axios in useEffect when the url parameter changes?

How can I rerun axios in useEffect when the url parameter changes?
Using a dependency
useEffect(() => {
axios.get(`http://myURL/employee_id/${someParam}`).then((response) => {
setEmployee(response.data);
});
}, [someParam]);
Although if I were you I would make the axios call inside changeId function directly. useEffect is overused sometimes. If you can make an action imperatively, there is no need to tie it to a variable and then track it also in useEffect for taking an action.

Related

Update in my WordPress Rest API data not flowing through to React

Ok so, I am using a wordpress Api and I am using react-query to retrun the data. The data is apearing as per normal. However, when I update the wordpress Api it is not catching the update. If I want to update the data that has been return in my browser I have to hard refresh.
enter image description here
I have tried to use isFetching to have refresh but it just returns as false so it's not reading the change. I am pretty stuck.
I have also tried building the traditional route of using axios.get etc but i have the same issue.

Fiori launchpad: handle logout event with custom backend call without `attachLogoutEvent` (UI5 < 1.81)

So, I found that the launchpad Container API provides an option to register a logout event with returning a promise (https://ui5.sap.com/#/api/sap.ushell.services.Container%23methods/attachLogoutEvent).
Unfortunately, after the implementation I found out that the UI5 version must be 1.81 or higher for parameter bAsync to work. In my project, we're at 1.78, so no promises for me.
What's the problem?
I want to make a backend call in the said logout event. This doesn't work, since, as far as I understood my debugging, the launchpad destroys everything just after my logout event has "finished" (= every line of code in the event has been gone through, ignoring sub-functions). Timeouts etc. don't work, because their calls would also be after code progressing has already finished, meaning the calls are deleted.
What have I tried?
Instant backend call without sub-functions → didn't work for the same reason as above.
Infinite while-looping until the backend call is processed → stack overflow.
While-looping with timeout/await → await not allowed in strict mode, timeout didn't work because of the above issue.
What do I think might work?
Stall code progression until the backend call has been finished.
Using a completely different method to get my logic into handling the logout (e.g. full custom logout).
Ask here for further ideas.
Does anyone have an idea on how to solve the issue with UI5 1.78?
Alright, I have found a solution to this. It's probably not the technically nicest, but it works and the result looks clean enough. This is from a S4/HANA system, so it might not be a universal solution (e.g. it doesn't consider logging off within the left-side pane which doesn't exist in my launchpad).
What did I do?
Instead of attaching my individual logic to the Fiori logout-event, I created a custom logout button with my individual logic, followed by calling the SICF logout node.
How did I do it?
Create a Launchpad plugin
In Component.js, add a new header item with custom logout function
// ushellLib required from "sap/ushell/library"
var oRenderer = ushellLib.Container.getRenderer("fiori2");
oRenderer.addHeaderEndItem("sap.ushell.ui.shell.ShellHeadItem", {
id: "logoutButton",
icon: "sap-icon://log",
// ...
press: [this._logout, this],
}, true, false);
_logout: function() {
this._callMyStuff();
window.location.href = "/sap/public/bc/icf/logoff";
},
In style.css, hide the original logout button (logoutBtn) in desktop (__list0...) and mobile (__list1...) to prevent skipping my logic by logging off via default logout.
#__list0-7-logoutBtn {
display: none;
}
#__list1-7-logoutBtn {
display: none;
}

Sails.js execute a middleware just before the controller action

I am developing an installable sails-hook that injects some checking on the request before allowing it to pass through the controller action. I want the checking to be done via installable hook, not as a policy, as I will be using the hook in other projects as well.
So, I am doing something like this inside my hook
sails.on('router:before', function() {
//attach middlewares here
sails.router.bind('/route', function(req, res, next) {
//do checking here. if everything is fine, call next()
req.options.controller // ?
}
});
The problem with the above apporach is that the req.options object does not contain the controller and action properties that my middleware depends upon (not now, may be in future).
So, what is the bestway to achieve this? One possible solution is to explicitly attach a policy that executes the middleware. I am looking for better options. Thanks

How do I make arbitrary API calls using Ember.js?

What I'm trying to do is described in great detail here:
Call a Server-side Method on a Resource in a RESTful Way
I have Ember Data's RESTAdapter working with my API, but now I want to give Ember.js a way to kick off various server-side actions using custom routes, such as /docs/1/share or /docs/1/activate. The former would possibly modify the record but the latter would not.
What's the best way to do this?
TIA!
Ember has jQuery baked in. In your controller:
actions: {
activate: function() {
var docId= this.get('id'), self= this;
Ember.$.ajax({
url: '/docs/%#/activate'.fmt(docId),
// your other details...
}).then(function(resolve) {
self.set('name', resolve.doc.name);
// process the result...
});
}
}
You can also use ic-ajax which is a nice wrapper around jQuery.ajax, you can see an example here using ix-ajax.

Where does related logic go on model creation when working with REST api with Django, Backbone, and Tastypie?

We are trying to move some of our app to use backbone and tastypie. I have the REST api set up and it is working on some basic examples. However, there are a few issues where currently we post an ajax request to a custom url, and in that view do a few things like
make related objects
call a few related functions
However, now that I've switched some of this functionality to using backbone and the REST api, I'm not sure where all of that should go!
For example, I had a view to make a Message, and when I made a Message, I also made a Notification and called a function to add some points to the user. Something like
def ajax_send_message(request):
## ... set up some variables ...
## Make the new message
message = Message(user=user, content=message)
message.save()
## Make the notification
notification = Notification(message=message)
notification.save()
## Give the user points
user.add_points_for_message();
return json_response({"status": "ok"})
Now--am I just supposed to do this all in JavaScript? I have a Message Backbone model as well.
// Create message backbone object
var msg = new Message({content:content, user: user});
// Post to server
msg.save();
// Add to backbone collection
messages.add(msg);
I've looked at different parts of tastypie, and it seems you can create custom URL endpoints, and also do validation, but that doesnt seem like the right spot to call related methods. It seems that calling related methods goes against the REST part of it---but then where are they supposed to go?
If I want to add some logic to backbone only when an object is created, where does that go?
The first thing I would suggest is to switch your mindset to an event-based model, where your code reacts to events. In your example above, you save the model to the server then immediately dd it to the collection. How do you even know that the model was saved correctly? That procedural style of programming works better in a synchronous, server-side style of programming.
In the asynchronous world of client-side programming, you make a request and then set up callbacks which determine what will happen next, depending on the events your are listening for. In your case, you want to react a certain way when the message is saved successfully, correct? You can define a success callback for your save operation like so:
msg.save({
success: function(model, response, options) {
messages.add(model);
// code to add notification
// code to add points
}
});
Basically, you are saying "I would like to save this model, and then listen for a success event. When the event comes in, execute the following code." Notice also that I am adding the model returned from the API to the collection, since this is the exact object that was persisted to the server so it's more appropriate to add than the model you created.