trigger branch io without open url - branch

I'm trying to implement in my app in react native app which I can trigger the branch without open url when I scan QR.
here I'm register with the branch
componentDidMount() {
this._unsubscribeFromBranch = branch.subscribe(({ error, params }) => {
if (error) {
console.error("Error from Branch: " + error)
return
}
console.log("Branch params: " + JSON.stringify(params));
if (params) {
this.setState({ scan: { ...this.state.scan, glassHash: params.hash } }, () => {
this._getCurrentPosition();
});
}
});
}
when I scan with Qr it run the function onSuccess and I want to trigger this branch.subscribe without openURL. if i openURL it works fine but it's not what i want
onSuccess(e) {
console.log(e);
// here i want to trigger the branch
this.setState({ barcodeText: e.data });
console.log(e);
}
i found on react-native-branch-deep-links docs about BranchEvent but I don't see any example about it.
I found this
new BranchEvent("UserScannedItem", buo).logEvent()
but not sure how to implement my custom event

Jackie from Branch here.
Branch links do function properly and retain the data when they are used with QR scanners, including dynamic query parameters (params appended behind the URL). If a QR code was used to open the app, you can retrieve the session data by using getLatestReferringParams(). Here's a sample code snippet on reading deep link data:
branch.subscribe(({ error, params }) => {
if (error) {
console.error('Error from Branch: ' + error)
return
}
// params will never be null if error is null
})
let lastParams = await branch.getLatestReferringParams() // params from last open
let installParams = await branch.getFirstReferringParams() // params from original install
More information on using getLatestReferringParams to handle link opens: https://docs.branch.io/pages/apps/react-native/#using-getlatestreferringparams-to-handle-link-opens
Regarding custom events, here's a sample class for generating standard and custom events with the Branch SDK: https://github.com/BranchMetrics/react-native-branch-deep-linking/blob/63cfc566ea45a6af0663fc7530c36fdb5dbf75e6/src/BranchEvent.js
If you are still having issues, please send over a screenshot of an example QR code with the associated Branch link directly to support#branch.io and I'd be happy to do some testing!
Best,
Jackie

Related

Sveltekit: Can't call API from +layout.ts. Error: "Failed to parse URL from /api/..."

This is the code in my +layout.ts
import type { LayoutLoad } from './$types';
export const load: LayoutLoad = async () => {
const response = await fetch('/api/thumbnails', { method: 'GET' })
if (response.ok) {
return { json: await response.json() }
}
else {
console.log('There were no blog posts to get.')
// TODO: do something!
}
};
I had the exact same code in a +page.ts file (the only difference was LayoutLoad was changed to PageLoad), and it worked there. I was calling my thumbnails api and populating my page. I don't understand why it doesn't work at all in +layout. It just crashes my web app.
On top of this, LayoutLoad has an error in VsCode that reads Module '"./$types"' has no exported member 'LayoutLoad'. I don't understand why this is. Can somebody help me?
I figured it out, the answer was here: https://kit.svelte.dev/docs/load#making-fetch-requests
To get data from an external API or a +server.js handler, you can use the provided fetch function, which behaves identically to the native fetch web API with a few additional features:
Basically, in my code I had to change this line
export const load: LayoutLoad = async () => {
to this
export const load: LayoutLoad = async ({fetch}) => {
Because without that change I was using the native fetch and not sveltekit's provided fetch.
Also, I seemed to have fixed this error: Module '"./$types"' has no exported member 'LayoutLoad' by updating sveltkit to the latest version.

Issue rendering data from firestore document in react native

I created a map for the array of exercises in my database, and then for each exercise, which is a document reference, I'm getting the data from that document reference and setting it to a state. This is resulting in an infinite loop right now.
If I remove the setExerciseData line, the console logs the exercise object's data that I'm expecting to see. I'm really not sure what the correct way to render the name field from this data is.
{workout.exercises.map((exercise) => {
async function getData(exercise) {
getDoc(exercise).then((doc) => {
console.log(doc.data());
setExerciseData(doc.data());
});
}
getData(exercise);
return (
<Text>{exerciseData.name}</Text>
)
})}
You need to use useEffect() and setState() to be able to render your data. Also, Firebase Firestore is Asynchronous in nature, as a general note, no one should be trying to convert an Async operation into a sync operation as this will cause problems. You need to use an Asynchronous function to fetch data from Firestore. See sample code below:
const getExerciseData = async () => {
const docRef = doc(db, "<collection-name>", '<document-id>')
const docSnap = await getDoc(docRef)
if (docSnap.exists()) {
// console.log("Document data:", docSnap.data())
setExerciseData(docSnap.data())
} else {
// doc.data() will be undefined in this case
console.log("No such document!")
}
}
useEffect(() => {
getExerciseData()
}, [])
return (
<Text>{exerciseData.name}</Text>
)
You could also check my answer on this thread for more use-cases.

Deferred Deep Linking in iOS using Branch.io in a React Native App

We have implemented deferred deep linking in our branch using Branch.io. The flow works correctly in our Android build but not in iOS. When clicking on a deep link in an iOS device the app is correctly installed but the deferred content piece of our deep link is not working. The branch validate gem is all green.
The relevant code is:
branch.subscribe(async ({ error, params, uri }) => {
if (error) {
console.error(`Error from Branch: ${error}`);
return;
}
if (params['+non_branch_link']) {
return;
}
if (!params['+clicked_branch_link']) {
return;
}
const deepLink = params.$deeplink_path;
if (deepLink) {
Linking.openURL(deepLink).catch((e) => { console.log('[Branch Error]', e); });
}
});
Never was able to solve this with existing paradigm. Ended up just setting state inside of my if block and redirecting the user on the incorrect screen if the state was set. Must be some kind of race condition.
¯\ (ツ)/¯
Did you try to set a initSessionTtl time of about 10 seconds?
componentDidMount() {
branch.initSessionTtl = 10000;
branch.subscribe(({ error, params, uri }) => {
//Handle the deep link here
});
}

React-native : how to check if it's the user's first connection?

I 'm new to react-native and I would like to set up my first page of the app with
1- The user never logged in the app, I 'll present the app with some slides + go to signup page
2 -The user is already in => directly go to the user page
3 -The user is already in but the id is not correct
Can you guide me through it ?
For the first point I really don't know how to check if the user exist in my db
For the second and third points I thought I'd try :
onPressLogin(){
fetch('linktomyAPI',{
method: 'POST',
headers:{
'Content-Type' : 'application/json',
'Accept':'application/json'
},
body: JSON.stringify({
username:this.state.username,
password: this.state.password,
})
})
.then(response => response.json())
.then((responseData) =>{
if(responseData.error !== 1){ // verify the success case, as you didn't provide the success case i am using the error code
this.setState({ // its recommended you verify the json before setting it to state.
userdetail: responseData,
})
setTimeout(() => {
Actions.Authentication();
}, 2300);
AsyncStorage.setItem('username', this.state.username); // its setItem not saveitem.
} else {
console.log(responseData);
Alert.alert(JSON.stringify(responseData)); // Alerts doesn't allow arrays or JSONs, so stringify them to view in Alerts
}
}).catch((error) => {
// handle catch
console.log("error:"+JSON.stringify(error));
});
}
Do you think I can do this way, is that relevant?
Thanks for taking the time to answer me. I'm really new so I need help and explanations. Thanks !!! :)
you can use the UserInfo to do. firstly, you have saved the user info in memory use Session js and in the device local file use AsyncStore. you already do it use the AsyncStore.
firstly save the user info into Session,the Session structure is:{id:"dd333",name:"john"},
...
setTimeout(() => {
Actions.Authentication();
}, 2300);
Session.id = res.id;
Session.name = res.name;
AsyncStorage.setItem('userinfo', Json.stringfy(res));
then you can show diffent page and condition.
// in the component which you want compoentDidMount
componentDidMount() {
// here you can try to get it from AsyncStore if the Session is null.
// then hanle it as the followng
if(Session.id == ""){
//default it is "", it means the user does not login
} else if(Session.id != "222"){
// the user id is not correct
} else {
// here is the user login and id is correct
}
}

Nuxt: Inside a plugin, how to add dynamic script tag to head?

I'm trying to build a Google Analytics plugin to Nuxt that will fetch tracking IDs from the CMS. I am really close I think.
I have a plugin file loading on client side only. The plugin is loaded from nuxt.config.js via the plugins:[{ src: '~/plugins/google-gtag.js', mode: 'client' }] array.
From there the main problem is that the gtag script needs the UA code in it's URL, so I can't just add that into the regular script object in nuxt.config.js. I need to get those UA codes from the store (which is hydrated form nuxtServerInit.
So I'm using head.script.push in the plugin to add the gtag script with the UA code in the URL. But that doesn't result in the script being added on first page load, but it does for all subsequent page transitions. So clearly I'm running head.script.push too late in the render of the page.
But I don't know how else to fetch tracking IDs, then add script's to the head.
// plugins/google.gtag.client.js with "mode": "client
export default ({ store, app: { head, router, context } }, inject) => {
// Remove any empty tracking codes
const codes = store.state.siteMeta.gaTrackingCodes.filter(Boolean)
// Add script tag to head
head.script.push({
src: `https://www.googletagmanager.com/gtag/js?id=${codes[0]}`,
async: true
})
console.log('added script')
// Include Google gtag code and inject it (so this.$gtag works in pages/components)
window.dataLayer = window.dataLayer || []
function gtag() {
dataLayer.push(arguments)
}
inject('gtag', gtag)
gtag('js', new Date())
// Add tracking codes from Vuex store
codes.forEach(code => {
gtag('config', code, {
send_page_view: false // necessary to avoid duplicated page track on first page load
})
console.log('installed code', code)
// After each router transition, log page event to Google for each code
router.afterEach(to => {
gtag('event', 'page_view', { page_path: to.fullPath })
console.log('afterEach', code)
})
})
}
I ended up getting this to work and we use it in production here.
Code as of this writing looks like this:
export default ({ store, app: { router, context } }, inject) => {
// Remove any empty tracking codes
let codes = _get(store, "state.siteMeta.gaTrackingCodes", [])
codes = codes.filter(Boolean)
// Abort if no codes
if (!codes.length) {
if (context.isDev) console.log("No Google Anlaytics tracking codes set")
inject("gtag", () => {})
return
}
// Abort if in Dev mode, but inject dummy functions so $gtag events don't throw errors
if (context.isDev) {
console.log("No Google Anlaytics tracking becuase your are in Dev mode")
inject("gtag", () => {})
return
}
// Abort if we already added script to head
let gtagScript = document.getElementById("gtag")
if (gtagScript) {
return
}
// Add script tag to head
let script = document.createElement("script")
script.async = true
script.id = "gtag"
script.src = "//www.googletagmanager.com/gtag/js"
document.head.appendChild(script)
// Include Google gtag code and inject it (so this.$gtag works in pages/components)
window.dataLayer = window.dataLayer || []
function gtag() {
dataLayer.push(arguments)
}
inject("gtag", gtag)
gtag("js", new Date())
// Add tracking codes from Vuex store
codes.forEach(code => {
gtag("config", code, {
send_page_view: false // Necessary to avoid duplicated page track on first page load
})
// After each router transition, log page event to Google for each code
router.afterEach(to => {
gtag("event", code, { page_path: to.fullPath })
})
})
}
If not in a plug-in, this was a good read on how to load 3rd party scripts: How to Load Third-Party Scripts in Nuxt.js