Add query parameter in the middle of the URL using react fetch - reactjs

I am writing a service for all my RestApis where I store RestApis and then use it when I need by calling methods.
RestApiService.js
let getData = 'https://myURL?id=123456';
export const getIndividualUsers = (resourceId) => {
const queryParams = {
userId: resourceId
};
queryParams.authorization = sessionStorage.getItem("authorization");
}
Object.keys(queryParams).forEach((k) => {
queryParams[k] = (typeof (queryParams[k]) !== 'string') ? JSON.stringify(queryParams[k]) : queryParams[k];
});
return getData.get('', queryParams);
};
I call this method when I need data using the method name and use the response in my code:
getIndividualUsers(123456).then((response));
Now one of my API has variable in the middle of the URL such as
URL: 'https://myURL/${variable}/children/12'
How do I pass queryParams(variable) in the middle of the Url? I will have variable value when I call the method that fetches the URL and not while defining the the URL.

Which library are you using? Anyway you can do like below always.
const getChild = (parentName, id) => {
let url = `https://myURL/${parentName}/children/${id}`;
...
};

Related

SvelteKit form get request

I am trying to set up a simple endpoint in SvelteKit that reads the input given in a form and returns the result of an SQL query. In my first attempt I used the form actions and wrote the following code in the +page.server.js file:
export const actions = {
default: async (event) => {
let form_input = await event.request.formData();
let query = {
text: "select * from ux_return_shipments($1, $2, $3, $4)",
values: [form_input.get('beg-dep-date') || null, form_input.get('end-dep-date') || null, form_input.get('beg-arr-date') || null, form_input.get('end-arr-date') || null
}
try {
const result = await event.locals.pool.query(query);
return result.rows;
} catch (e) {
console.log(e);
}
}
};
I am now trying to set up the same process using a GET request instead of a POST one but I am having difficulties setting up the endpoint. I tried to replace the above code with this template but it looks like the endpoint is not getting activated since I see no activity server side:
export function GET({ url }) {
console.log(url);
return new Response("Test response");
};
What am I doing wrong? I see that using this code for an API endpoint (+server.js file) works correctly. I also checked the form element and the URL looks correct.
In case someone has the same problem I managed to solve it using this template:
export const load = async (event) => {
return ...
};
Using the load function I was able to set up a get endpoint and pass some data to the frontend using a return.

React: Method finishing before data loaded

I am trying to retrieve some data from Yahoo Finance using an XHTML Request, which works. However, I am trying to display the data retrieved on my app, but the method to retrieve the data is returning "undefined" before the data has been loaded.
async componentDidMount() {
var tempData = await this.fetchAsync();
console.log(tempData)
this.handleLoad(tempData)
}
handleLoad = (num) => {
this.setState(state => ({
price: num
}));
}
async fetchAsync () {
const xhr = new XMLHttpRequest();
xhr.withCredentials = true;
const {params} = this.props.navigation.state;
var ticker = params.ticker;
var result;
var tempArray = [1];
var url = "https://yahoo-finance-low-latency.p.rapidapi.com/v8/finance/spark?symbols=" + ticker + "&range=2y&interval=1d"
xhr.addEventListener("readystatechange", function () {
if (this.readyState === this.DONE) {
result = JSON.parse(this.responseText);
tempArray = result[ticker]['close'];
testPrice = tempArray[tempArray.length-1]
console.log(testPrice)
var self = this;
return tempArray[tempArray.length-1]
}
});
xhr.open('get', url, true);
xhr.setRequestHeader("x-rapidapi-key", "my key");
xhr.setRequestHeader("x-rapidapi-host", "yahoo-finance-low-latency.p.rapidapi.com");
xhr.send();
}
I am using the componentDidMount() function to begin calling the methods to load the data, but when the app renders, the values are not displayed.
As you can see inside the fetchAsync() method, I return the value I need, but when I try and console.log the return from this method, I get undefined.
I have also tried moving this return to the end of the method, but when I use console.log here to ensure that tempArray has the data I need, it is empty.
I need to display tempArray[tempArray.length-1] on my screen, but the data is not loaded in time, and does not update even after it has loaded.
Your return tempArray[tempArray.length-1] inside the fetchAsync isn't actually returning from fetchAsync -- it's just returning from the callback function inside addEventListener. In fact, you don't actually have any code that is taking advantage of the async tag you have on that function.
One solution to this would be to call handleLoad directly from inside fetchAsync instead of return tempArray. (Of course, you'll want to make sure that you've bound this correctly to handleLoad).
Another solution would be to pass a callback function into fetchAsync that you could call instead of returning. Then, at your call site, it might look something like this:
this.fetchAsync((tempData) => {
console.log(tempData)
this.handleLoad(tempData)
});
Finally, a third solution would be to switch from XMLHTTPRequest to fetch, and then you could take advantage of async/await and actually make that fetchAsync method async (and be able to return a value from it).

How to get acess to the query argument followed after a questionmark?

After searching for a product inside a search box, my app executes a get request on
"localhost/api/products?searchword".
Now i want to build an express api, that searches for the searchword inside my db.
How do i get access to the searchword?
I tried with req.query.name but it only works with a link like
"localhost/api/products?name=searchword".
How do i get access with my specific link
I have an express API endpoint that does exactly that.
I call it using this URL structure: /blog/search?q=some+search+string
export const blogSearch: RequestHandler = async (req, res) => {
const queryString = (req.query.q || "");
// ...
}
In order to use req.query, you should use the ?key1=value1,key2=value2 structure.
http://expressjs.com/en/api.html#req.query
If you want to manually parse the queryString, you can use req.url and you'll get the /api/products?searchword, so you can split it on the ? the read your searchWord.
Maybe someone will encounter the same problem, so i want to post my code that worked
router.get('/',
expressAsyncHandler( async (req, res)=> {
const name = req.url.split('?')[1] || "";
console.log(name);
const nameFilter= name ? { title: {$regex: name, $options: 'i'} } : {};
const products = await Product.find({
...nameFilter,
}).populate();
res.send(products);
})
);

getting a value from a field in firebase

I am trying to retrieve a specific value of a field and store it inside a variable named joiningScore. This makes joiningScore a object with a promise that has a value in it. How can I get that value. I tried tucking in a .then method after the .get("currentPos") but it throws an error saying docSnapshot.get().then is not a function.
var joiningScore = positionDoc.get().then((docSnapshot) => { return docSnapshot.get("currentPos"); })
const positionDoc = frebase.firestore().collection('position').doc('kY3k3lmnCIVG3Qi6LxUZ');
here positionDoc is a reference to the document in firestore.
This is because you are assigning to a variable a Promise chain.
You need to wait that the Promise returned by the get() method is fulfilled in order to get the value. See this doc for more details.
So something along these line should work:
const positionDoc = firebase.firestore().collection('position').doc('kY3k3lmnCIVG3Qi6LxUZ');
var joiningScore;
positionDoc.get().then((docSnapshot) => {
joiningScore = docSnapshot.get("currentPos");
})
You could also use an async function as follows:
async function getJoiningScore() {
const positionDoc = firebase.firestore().collection('position').doc('kY3k3lmnCIVG3Qi6LxUZ');
const docSnapshot = await positionDoc.get();
return docSnapshot.get("currentPos");
}
Note that this function is itself asynchronous.

react-router generatePath with query parameters

I am using react-router's built in function generatePath to generate a URL. The issue is that as far as I understand this function just returns the path and doesn't provide a mechanism for us to know which fields were added in the path and which were not.
For example, for the following code
generatePath('/user/:id', {
id: 1,
name: 'John',
})
the function returns /user/1 which is correct, but there is no way for us to know that only id was inserted into the path and name needs to be passed as query parameters.
In my application both the path template and the params object are dynamic and I need to add the extra fields in params as the query parameters.
Is there any way to do that ?
For anyone checking now, I ended up using the path-to-regexp library which is the one used internally by react-router to generate the URL. The code looks something like this
import pathToRegexp from 'path-to-regexp';
import qs from 'qs';
const compiledCache = {};
export default function generatePathWithQueryParams(rawPath, params) {
let toPath;
if (compiledCache[rawPath]) {
toPath = compiledCache[rawPath];
} else {
toPath = pathToRegexp.compile(rawPath);
compiledCache[rawPath] = toPath;
}
const queryParams = { ...params };
const path = toPath(params, {
encode: (value, token) => {
delete queryParams[token.name];
return encodeURI(value);
},
});
const queryString = qs.stringify(queryParams);
if (queryString) {
return `${path}?${queryString}`;
}
return path;
};

Resources