I am working on a React project, and I have 2 functions "functionGetDataBase" and "getMapBoxAddresses". The first function gets massive data, then the data goes into the "gatMapboxAddresses" function, and then console log the data in order to use the data for something else.
const functionGetDataFireBase = async () => {
const dataFirebaseRes = await getDataFireBase();
const data = await getMapboxAddresses(dataFirebaseRes);
console.log(data);
};
functionGetDataFireBase();
export async function getMapboxAddresses(dataFromFirebase) {
// eslint-disable-next-line no-unused-vars
const mapBapboxAddressesRes = [];
const tokenKey = `xxxxx`;
for (const userData of dataFromFirebase) {
const modifiedAddresses = userData.Addresses.replace(/ /g, "%20");
const url = `https://api.mapbox.com/geocoding/v5/mapbox.places/${modifiedAddresses}.json?country=ca&fuzzyMatch=true&routing=true&proximity=-75.90307073393681%2C45.3283659706355&language=en&access_token=${tokenKey}`;
const resMap = await fetch(url);
const resJSON = await resMap.json();
console.log(resJSON);
}
return mapBapboxAddressesRes;
}
However, the request for any reason does not get all the url for some of the userData of dataFromFirebase as was expected.
url number 1 : expected url
url number 2 : result
1. https://api.mapbox.com/geocoding/v5/mapbox.places/1000%20Innovation%20Drive%20Suite%20500.json?country=ca&fuzzyMatch=true&routing=true&proximity=-75.90307073393681%2C45.3283659706355&language=en&access_token=xxx
2. https://api.mapbox.com/geocoding/v5/mapbox.places/1285%20Teron%20Road%20
encodeURIComponent() is a more comprehensive way to make values safe in a URL.
const modifiedAddresses = encodeURIComponent(userData.Addresses);
I imagine some of your Addresses
values have incompatible characters like newlines, etc.
Further advice would be to use the URLSearchParams interface to construct the entire thing safely.
const baseURL = "https://api.mapbox.com/geocoding/v5/mapbox.places/";
const params = new URLSearchParams({
country: "ca",
fuzzyMatch: "true",
routing: "true",
proximity: "-75.90307073393681,45.3283659706355",
language: "en",
access_token: tokenKey,
}).toString();
const mapBapboxAddressesRes = await Promise.all(
dataFromFirebase.map(async (userData) => {
const url = `${baseURL}${encodeURIComponent(
userData.Addresses,
)}.json?${params}`;
const resMap = await fetch(url);
if (!resMap.ok) {
throw new Error(`Fetch failed for ${url}`);
}
return resMap.json();
}),
);