Javascript Axios get with conditional params - javascript

I am trying to get some data from an API. The problem is that the GET call could take none or some of the filters. I have tried but am not sure how/if I can create a URL with conditional filters.
actions: {
InstitutionSearch(value, id){
let fips = id['ParamValues'].find(o=>o.param==='fips')['value'];
let region = id['ParamValues'].find(o=>o.param==='region')['value'];
axios.get('https://educationdata.urban.org/api/v1/college-university/ipeds/directory/2019/',{
params:{
fips: ,
region: region,
offering_highest_level: 3
}
})
};
}
This is a vue application, with the code above running inside a vuex store. The id that is being passed in is an array of objects, that is taken from a search filter form. The problem that I have is that my query could include either fips or region or none.
My initial thought was the put fips and region equal to 0, but that does not work with my API. I am not opposed to building a query string inside conditionals, but there has to be an easier way. The following is an actual query for the data that I am working with https://educationdata.urban.org/api/v1/college-university/ipeds/directory/2019/?offering_highest_level=3.

With some amazing help, I figured out a simple solution. I created an empty object and then ran a conditional check on my parameters and only added them, if they met my qualifications. I then passed that object in as the parameters, and everything worked.
let fips = id['ParamValues'].find(o=>o.param==='fips')['value'];
let region = id['ParamValues'].find(o=>o.param==='region')['value'];
//code change
let params = {};
fips.length > 0 ? params['fips'] = fips.join(',') : null;
region != 0 ? params['region'] = region : null;
//code change
axios.get('https://educationdata.urban.org/api/v1/college-university/ipeds/directory/2019/',{
params
}).then(response=>{
console.log(response.data.results);
});

useEffect(() => {
axios
.get(
`http://stream-restaurant-menu-svc.herokuapp.com/item?category=${props.data}`
)
.then((response) => {
console.log("This is to show sub-categoary " + response.data);
setSubcate(response.data);
})
.catch((error) => {
console.log(error);
});
},[props]);

Related

How do I create an array from Promise results?

I'm using React to build a web app. At one point I have a list of ids, and I want to use those to retrieve a list of items from a database, get a list of metrics from each one, and then push those metrics to an array. My code so far is:
useEffect(() => {
const newMetrics = [];
currentItems.forEach((item) => {
const url = `items/listmetrics/${item.id}`;
Client.getData(url).then(async (metrics) => {
let promises = metrics.map((metricId: string) => {
// Get metric info
const urlMetric = `metrics/${metricId}`;
return Client.getData(urlMetric);
});
await Promise.all(promises).then((metrics: Array<any>) => {
metrics.forEach((metric: MetricModel) => {
const metricItem = {
id: metric.id,
metricName: metric.name
};
newMetrics.push(metricItem);
}
});
});
});
setMetrics(newMetrics);
});
}, [currentItems]);
where "metrics" is a state variable, set by setMetrics.
This appears to work ok, but when I try to access the resulting metrics array, it seems to be in the wrong format. If I try to read the value of metrics[0], it says it's undefined (although I know there are several items in metrics). Looking at it in the console, metrics looks like this:
However, normally the console shows arrays like this (this is a different variable, I'm just showing how it's listed with (2) [{...},{...}], whereas the one I've created shows as []):
I'm not confident with using Promise.all, so I suspect that that's where I've gone wrong, but I don't know how to fix it.

How do I only render the updated stat - websockets

right now the entire div re-renders, but I am searching for a way to only re-render the updated statistic
these are parts of what I have now
updatestats.js
document.querySelector("#submit").addEventListener("click", function (e) {
let country = document.querySelector("#country").value
let numberCases = document.querySelector("#number").value
fetch(base_url + "/api/v1/stats/updatestats", {
method: "put",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify({
"country": country,
"numberCases": numberCases
})
}).catch(err => {
console.log(err);
})
primus.write({ "action": "update" })
stats.js
primus.on("data", (json) => {
if (json.action === "update") {
document.querySelector("#overview").innerHTML = ""
appendInfo()
}
})
function appendInfo() {
fetch(base_url + "/api/v1/stats", {
method: "get",
headers: {
'Content-Type': 'application/json'
},
}).then(response => {
return response.json();
}).then(json => {
json.data.stats.forEach(stat => {
let country = stat.country
let numberCases = stat.numberCases
let p = document.createElement('p')
let text = document.createTextNode(`${country}: ${numberCases}`)
p.appendChild(text)
let overview = document.querySelector("#overview")
overview.appendChild(p)
})
}).catch(err => {
console.log(err);
})
}
window.onload = appendInfo();
stats.pug
body
h1 Cases by country
div#overview
So if I only update the country Belgium I only want that statistic to be changed. Now everything seems to reload
What I meant with my suggestion is to keep te communication of data between client and server strictly in the sockets. Meaning when one user updates 1 value on their end, that value will be send to the server and stored. After the server finished storing the value, that same value will be sent to all other clients. This way you only send and receive the parts that have been changed without having to download everything on every change.
I might not be able to write the code exactly as it should be as I have limited experience with Primus.js and know little about your backend.
But I would think that your frontend part would look something like this. In the example below I've removed the fetch function from the click event. Instead send the changed data to the server which should handle those expensive tasks.
const countryElement = document.querySelector("#country");
const numberCasesElement = document.querySelector("#number");
const submitButton = document.querySelector("#submit");
submitButton.addEventListener("click", function (e) {
let data = {
action: 'update',
country: countryElement.value,
numberCases: numberCasesElement.value
};
primus.write(data);
});
Now the server should get a message that one of the clients has updated some of the data. And should do something with that data, like storing it and letting the other clients know that this piece of data has been updated.
primus.on('data', data => {
const { action } = data;
if (action === 'update') {
// Function that saves the data that the socket received.
// saveData(data) for example.
// Send changed data to all clients.
primus.write(data);
}
});
The server should now have stored the changes and broadcasted the change to all other clients. Now you yourself and other will receive the data that has been changed and can now render it. So back to the frontend. We do the same trick as on the server by listening for the data event and check the action in the data object to figure out what to do.
You'll need a way to figure out how to target the elements which you want to change, you could do this by having id attributes on your elements that correspond with the data. So for example you want to change the 'Belgium' paragraph then it would come in handy if there is a way to recognize it. I won't go into that too much but just create something simple which might do the trick.
In the HTML example below I've given the paragraph an id. This id is the same as the country value that you want to update. This is a unique identifier to find the element that you want to update. Or even create if it is not there.
The JavaScript example after that receives the data from the server through the sockets and checks the action. This is the same data that we send to the server, but only now when everybody received we do something with it.
I've written a function that will update the data in your HTML. It will check for an element with the id that matches the country and updates the textContent property accordingly. This is almost the same as using document.createTextNode but with less steps.
<div id="overview">
<p id="Belgium">Belgium: 120</p>
</div>
const overview = document.querySelector("#overview");
primus.on('data', data => {
const { action } = data;
if (action === 'update') {
updateInfo(data);
}
});
function updateInfo(data) {
const { country, numberCases } = data;
// Select existing element with country data.
const countryElement = overview.querySelector(`#${country}`);
// Check if the element is already there, if not, then create it.
// Otherwise update the values.
if (countryElement === null) {
const paragraph = document.createElement('p');
paragraph.id = country;
paragraph.textContent = `${country}: ${numberCases}`;
overview.append(paragraph);
} else {
countryElement.textContent = `${country}: ${numberCases}`;
}
}
I hope that this is what you are looking for and / or is helpful for what you are trying to create. I want to say again that this is an example of how it could work and has not been tested on my end.
If you have any questions or I have been unclear, then please don't hesitate to ask.
To elaborate #EmielZuurbier's suggestion in the comment, please try the following code.
//Client-side
primus.emit('data',data);
primus.on("dataUpdated", (json) => {
});
//Server-side
primus.on('data',data =>{
//process it here and then
//send it out again
primus.emit('dataUpdated','the data you want to send to the front end');
})

Async issue with State in React Native

I'm trying to build a simple app that lets the user type a name of a movie in a search bar, and get a list of all the movies related to that name (from an external public API).
I have a problem with the actual state updating.
If a user will type "Star", the list will show just movies with "Sta". So if the user would like to see the actual list of "Star" movies, he'd need to type "Star " (with an extra char to update the previous state).
In other words, the search query is one char behind the State.
How should it be written in React Native?
state = {
query: "",
data: []
};
searchUpdate = e => {
let query = this.state.query;
this.setState({ query: e }, () => {
if (query.length > 2) {
this.searchQuery(query.toLowerCase());
}
});
};
searchQuery = async query => {
try {
const get = await fetch(`${API.URL}/?s=${query}&${API.KEY}`);
const get2 = await get.json();
const data = get2.Search; // .Search is to get the actual array from the json
this.setState({ data });
} catch (err) {
console.log(err);
}
};
You don't have to rely on state for the query, just get the value from the event in the change handler
searchUpdate = e => {
if(e.target.value.length > 2) {
this.searchQuery(e.target.value)
}
};
You could keep state updated as well if you need to in order to maintain the value of the input correctly, but you don't need it for the search.
However, to answer what you're problem is, you are getting the value of state.query from the previous state. The first line of your searchUpdate function is getting the value of your query from the current state, which doesn't yet contain the updated value that triggered the searchUpdate function.
I don't prefer to send api call every change of letters. You should send API just when user stop typing and this can achieved by debounce function from lodash
debounce-lodash
this is the best practise and best for user and server instead of sending 10 requests in long phases
the next thing You get the value from previous state you should do API call after changing state as
const changeStateQuery = query => {
this.setState({query}, () => {
//call api call after already changing state
})
}

Cloud Firestore query works sometimes but not always

This has me really stumped. I have a method that searches for items in a Firestore database. It works when I call the method directly from a one-off test. It does not work when I call the method from another part of my app with the exact same input.
Here is the method that does the searching:
getProductsStartingWithCategory(textSoFar: string): Observable<Product[]> {
console.log('searching for ', textSoFar);
let endAt = textSoFar + '\uf8ff';
let filteredCollection: AngularFirestoreCollection<Product> =
this.afs.collection('products', ref =>
ref.orderBy('materialType').limit(30).startAt(textSoFar).endAt(endAt)
);
return filteredCollection.snapshotChanges().map(changes => {
return changes.map(a => {
console.log('matched one', a);
const data = a.payload.doc.data() as Product;
data.id = a.payload.doc.id;
return data;
});
});
}
And when I call the method directly from the first page in the app with a test button, it works. That method is as follows:
testTheThing() {
let text: string = 'Car';
this.productService.getProductsStartingWithCategory(text)
.subscribe(data => {
console.log('success', data);
});
}
Again, when I call this method I get results as expected (matching products in the database with materialType 'Carpet'.) Success!
But then, when I use the method from another page in the app, it returns no results. That page is a bit more complicated - essentially the method is being called when user input changes. Here are the relevant parts of the method:
productCategoryChanged(productPurchase: ProductPurchase) {
if (productPurchase.materialType) {
console.log('searching for products starting with "' + productPurchase.materialType + '"');
let unsubscribe = this.productService.getProductsStartingWithCategory(productPurchase.materialType).subscribe(products => {
products.forEach(product => {
// logic goes here...
});
});
// rest of method omitted
In both scenarios, I see the "searching for Car" in the console.log message. The search text is identical. I've tried numerous times with numerous different search text (all of which are in the database). The logging shows the method is being called with the right input, but for some reason I only find results when calling it from the "test" method. Why is that?
I've tried trimming the input. I do have another collection of 'products' hooked up to an observable, but I don't think that matters. I also have used this exact strategy for a "customer" search and that works fine. This "products" search is almost identical but it doesn't work.

EmberJS is not loading up the model correctly

At a loss on this one.
I'm using Ember and Ember data. I've got this extra implementation of ic-ajax to make GET, POST and PUT calls. Anyway, i'm trying to make a GET call then turn those results into model instances.
return this.GET('/editor')
.then((data) => {
return data.drafts.map((draftData) => {
let draft = this.store.find('draft',draftData.id);
console.log(draft.get('type'));
return draft;
});
});
My API returns proper data as data.drafts. This map is supposed to return an array of promises that resolve to draft models. It does not. It resolves to a draft model that has id, date, and title. But that's it. I have 25 others attributions.
In another part of the application i'm getting drafts using findAll on the model. And those models look fine. But when I try store.findRecord('draft',id) i get these fake objects.
-- edit
This is what my ReOpenClass method looks like for getting an array of objects from the server and turning them into ember objects
search(critera) {
let query = { search: critera };
let adapter = this.store.adapterFor('application');
let url = adapter.buildURL('article','search');
return adapter.ajax(url,'GET', { data: query }).then(response => {
let articleRecords = response.articles.map((article) => {
let record;
try {
record = this.store.createRecord('article', article);
} catch(e) {
record = this.store.peekRecord('article', article.id);
}
return record;
});
return articleRecords;
});
},
So far I can't find a better way to pull this off.

Categories