I am trying to extract the code from an incoming url in react native. I am able to receive the url and print it in my console but having trouble getting the param from url.
My code:
useEffect(() => {
Linking.addEventListener('url', callback);
})
callback = async (url) => {
if (url !== null) {
const new_url = JSON.stringify(url)
console.log(new_url)
const urlCallback = new URL(new_url);
const code = urlCallback.searchParams.get('code');
console.log(code)
}
};
I keep getting this error: TypeError: Invalid URL: {"url":"myapp://?code=ABCDEFG"}
I am trying to query out that code so i can send it as a param in a post request.
Appreciate any help, thanks!
Based on the error message, it seems you're stringifying url object, not string. Try to parse from its 'url' prop instead.
callback = async (url) => {
if (url !== null) {
const new_url = url.url;
console.log(new_url)
const urlCallback = new URL(new_url);
const code = urlCallback.searchParams.get('code');
console.log(code)
}
};
Try this query-string
const parsed = queryString.parseUrl("myapp://?code=ABCDEFG");
console.log(parsed.query.code)
Related
how do I rewrite this code to accomodate the headers, using a different API everything works fine if set like this
const fetchData = async (params) => {
try {
setLoading(true);
const res = await axios.get(`https://api.publicapis.org/${query}`, params);
setResponse(res.data);
However, once I switch to add the headers while there is no error in VScode, I get 401 on console. When I remove query and params, it works fine.
const fetchData = async (params) => {
try {
setLoading(true);
const res = await axios.get(`https://api.url**/api/v1/content/${query}`, params,
{headers: {
'X-AUTH-TOKEN' : '22b********5c'}}) ;
setResponse(res.data.data);
//using data.data here as that is how the api is set up
api output
I have TextInput and I need to send request every time when the text is changing
I have this code:
// Main.js
import Api from 'network/ApiManager';
const api = new Api();
// TextInput onChangeText function
const getSearch = useCallback(
async (searchName, sectorTypeId, type, filterData) => {
const result = await api.controller.search(searchName, sectorTypeId, type, filterData);
console.log(result)
},
[],
);
And i have this network layer
// NetworkManager.js
async getData(url) {
try {
const {data: response} = await axios.get(url);
return response;
} catch (e) {
return response;
}
}
controller = {
profile: async (search, sector, f_type, filterData = {}) => {
const res = await this.getData('/url/path');
return this.transformToOptions(res);
},
};
When onChangeText is called, I send a lot of requests, but I want to cancel previous requests and get the latest only. I know that I need to use CancelToken but I don't know how to pass it on my network layer
Please help
You can create a cancelToken, whenever a request comes, you can save the cancel token, when a new request comes, cancelToken won't be undefined, thus you can call cancelToken.cancel(). Try something like this:
let cancelToken
if (typeof cancelToken != typeof undefined) {
cancelToken.cancel("Operation canceled due to new request.")
}
//Save the cancel token for the current request
cancelToken = axios.CancelToken.source()
try {
const results = await axios.get(
`Your URL here`,
{ cancelToken: cancelToken.token } //Pass the cancel token
)
https://obikes.page.link/d6o5/?ref=10959bc
I am using axios this is my invite link in my app i want to get data after query string i need ref code ref=10959bc ,how can i get this query data 10959bc in react native
i am unable to find any solution
React.useEffect(async () => {
const getValue = await AsyncStorage.getItem('token');
await getReferal().then(response => {
console.log(response.data.refferalUrl); //https://obikes.page.link/d6o5/?ref=10959bc
// refer code
})
.catch(error => {
console.log(error);
});
A pure JS approach:
React.useEffect(async () => {
const getValue = await AsyncStorage.getItem('token');
await getReferal().then(response => {
console.log(response.data.refferalUrl);
// refer code:
const url = response.data.refferalUrl
let regex = /[?&]([^=#]+)=([^&#]*)/g, params = {}, match;
while ((match = regex.exec(url))) {
params[match[1]] = match[2];
}
console.log(params) // => {ref: "10959bc"}
})
.catch(error => {
console.log(error);
});
Use the qs npm package to get the query string params from a string.
https://github.com/ljharb/qs
Im trying to find an efficient way to get the url of an image in firebase right after ive uploaded it.
Id like to avoid writing a totally separate function to this....and instead Id like to include it in the promise chain. See code below
import storage from '#react-native-firebase/storage';
storage()
.ref('path/to/remote/folder')
.putFile('uri/of/local/image')
.then(() => {
//Id like to use getDownloadUrl() function here;
})
You can create chain of promises using await and then easily get your download url as below :
/**
* Upload the image to the specific firebase path
* #param {String} uri Uri of the image
* #param {String} name Name of the image
* #param {String} firebasePath Firebase image path to store
*/
const uploadImage = async (uri, name, firebasePath) => {
const imageRef = storage().ref(`${firebasePath}/${name}`)
await imageRef.putFile(uri, { contentType: 'image/jpg'}).catch((error) => { throw error })
const url = await imageRef.getDownloadURL().catch((error) => { throw error });
return url
}
Now you can call this function as below :
const uploadedUrl = await uploadImage('uri/of/local/image', 'imageName.jpg', 'path/to/remote/folder');
Now uploadedUrl will contains url of the uploaded image.
Good answer from Kishan but did not work for me....below includes some minor modifications so would work for me.
const localUri = Platform.OS === 'ios' ? imgPickResponse.uri.replace('file://', '') : imgPickResponse.uri;
this.uploadImageAndGetUrl(localUri, '/profilePics/' + this.props.userId)
.then(url => {console.log(url);});
}
uploadImageAndGetUrl = async (localUri, firebasePath) => {
try {
const imageRef = storage().ref(firebasePath);
await imageRef.putFile(localUri, {contentType: 'image/jpg'});
const url = await imageRef.getDownloadURL();
return url;
} catch (err) {
Alert.alert(err);
}
};
In my case, uri threw an error with Android permissions. So following function worked for me. Instead of uri, I passed response.path from the ImagePicker. Tip: you can use uuid to generate random file name.
this.uploadAndReturnFirestoreLink(response.path, 'images/' + 'example.jpg')
uploadAndReturnFirestoreLink = async (loaclPath, folderPath) => {
console.log(loaclPath)
try {
const imageRef = storage().ref(folderPath);
await imageRef.putFile(loaclPath, { contentType: 'image/jpg' });
const url = await imageRef.getDownloadURL();
console.log(url)
alert('Upload Success', url)
} catch (e) {
console.log(e);
}
};
Please help with this problem
I'm trying to show registers from an api route (/api/orders)
When I call them from axios, I use get petittion to /api/orders
This is my method:
listarOrdenesIngreso (page,buscar,criterio) {
let me=this;
var url= '/api/orders?page=' + page + '&buscar='+ buscar +'&criterio='+ criterio;
axios.get(url)
.then(function (response) {
var respuesta= response.data;
me.arrayOrders = respuesta.orders.data;
me.pagination = respuesta.pagination;
// handle success
})
........
Here is the API route routes/api.php file
Route::resource('orders', 'EntryOrderController',['except' => ['create','edit']]);
and here the code of controller (EntryOrderController.php file)
public function index(Request $request)
{ if (!$request->ajax()) return redirect('/');
$entries = EntryOrder::all();
//return response()->json(['data' => $entries], 200);
return $this->showAll($entries);
}
The problem It shows in image 1, where not show any register in my vue component When I call them from the URL in the browser, show me correctly the array with data.
I hope you can help me Thanks
Your problem is the request result data not founded
`listarOrdenesIngreso (page,buscar,criterio){
let me=this;
var url= '/api/orders?page=' + page + '&buscar='+ buscar + '&criterio='+ criterio;
axios.get(url)
.then(function (response) {
me.pagination = response.pagination;
me.arrayOrders = response.data.data; // do this
//me.arrayOrders = respuesta.orders.data; // errors here
// handle success
})