Unable to access passed parameters from deep links in React Navigation V6

I'm currently working on setting up a simple linking logic to open an app via an invitation link. The link format would be something like this: [scheme]://auth/[invitaion-code]

To achieve this, I have set up the following linking object to pass to the NavigationContainer

const linking: LinkingOptions<RootStackParamList> = {
  prefixes: ['my app scheme'],
  config: {
    screens: {
      Authorizer: {
        path: "auth/:code",
      },
    },
  },
};

Additionally, I have defined the following navigation stack:

    <NavigationContainer ref={navigationRef} linking={linking}>
      <Stack.Navigator
        screenOptions={{ headerShown: false }}
        initialRouteName={initialRouteName}
      >
        <Stack.Screen name="Authorizer" component={AuthorizerView} />
      </Stack.Navigator>
    </NavigationContainer>

Now, my question is how can I access the code parameter inside my AuthorizerView Component?

I have attempted the following, but the value always comes out as undefined

const AuthorizerView: React.FC<Props> = ({ navigation }: Props) => {
  const {code} = navigation.params;

Here is the log of the navigation object:

{"addListener": [Function addListener], "canGoBack": [Function canGoBack], "dispatch": [Function dispatch], "getId": [Function getId], "getParent": [Function getParent], "getState": [Function anonymous], "goBack": [Function anonymous], "isFocused": [Function isFocused], "navigate": [Function anonymous], "pop": [Function anonymous], "popToTop": [Function anonymous], "push": [Function anonymous], "removeListener": [Function removeListener], "replace": [Function anonymous], "reset": [Function anonymous], "setOptions": [Function setOptions], "setParams": [Function anonymous]}

This issue is similar to this question, but none of the existing answers have proved successful for me, prompting me to ask this question anew.

Answer №1

To enhance your linking object, consider implementing a getInitialURL function and a subscribe method:

import * as Linking from "expo-linking";
import { URLListener } from "expo-linking";

/**
 * Retrieves the initial URL when the app is launched via a deep link.
 */
const getInitialURL = async () => {
  // Obtain the initial deep link URL
  const initialDeepLinkUrl = await Linking.getInitialURL();

  return initialDeepLinkUrl;
};

/**
 * Handles links during app runtime.
 */
const subscribe = (listener: (url: string) => void) => {
  // URL listener for Linking.addEventListener to trigger the provided listener
  const onReceiveURL: URLListener = ({ url }) => {
    listener(url);
  };

  // Subscribe to incoming links from deep linking
  const linkingSubscription = Linking.addEventListener("url", onReceiveURL);

  return () => {
    // Remove event listeners
    linkingSubscription.remove();
  };
};

Update your linking object with these additions:

const linking: LinkingOptions<RootStackParamList> = {
  prefixes: ["my app scheme"],
  config: {
    screens: {
      Authorizer: {
        path: "auth/:code",
      },
    },
  },
  getInitialURL,
  subscribe,
};

While this approach may be comprehensive, it was effective for handling notifications in my scenario. Consider adapting these methods for your own needs.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

`AngularJS Voice Recognition Solutions`

In my quest to implement voice recognition in an AngularJS application I'm developing for Android and Electron, I've encountered some challenges. While I've already discovered a suitable solution for Android using ng-speech-recognition, fin ...

Error message: There appears to be a type error within the labelFunc of the KeyBoardDatePicker component in the Material-UI

I am currently working with a material-ui pickers component: <KeyboardDatePicker value={selectedDate} onChange={(_, newValue) => handleClick(newValue)} labelFunc={renderLabel} disableToolbar variant='inline' inputVariant=& ...

Tips for specifying types in protractor.conf.js while utilizing the @ts-check feature

Within my Angular CLI v7.3.6 project, there is a protractor.conf.js file that I'm looking to enhance with @ts-check in VSCode. When using @ts-check, I aim to execute the browser.getCapabilities() function in the onPrepare() callback but encountered an ...

Learn how to use JavaScript to parse binary files

Is there a way to interpret this binary data below? Binary2 { sub_type: 0, buffer: Buffer(16) [ 12, 15, 64, 88, 174, 93, 16, 250, 162, 5, 122, 223, 16, 98, 207, 68 ], position: 16 } I've attempted different methods like using ...

Encountering an error message when trying to launch an application: Module

Every time I try to launch my react-native app in git-bash, I encounter the following error message. I have already uninstalled and reinstalled node.js, cleared the cache, and attempted various solutions from Stack Overflow and GitHub with no success. ...

Using Visual Studio Code, the next app created with nx now supports relative imports

I am encountering a problem with a Next.js project set up using nx and VS Code: When trying to automatically import a component in VS Code, it generates an absolute import which then triggers the @nrwl/nx/enforce-module-boundaries eslint rule, rendering t ...

Obtain the query response time/duration using react-query

Currently utilizing the useQuery function from react-query. I am interested in determining the duration between when the query was initiated and when it successfully completed. I have been unable to identify this information using the return type or para ...

Creating a personalized HTML email template with a TypeScript foreach loop

As I work on developing an app, users will have the opportunity to share product information via email. Each product includes a title, image, description, ingredients, and a list of energy values. Currently, I am able to send an email with all the product ...

Best Practices for Updating UI State in Client Components Using NextJS and Server Actions

My goal is to create a page using nextjs 14 that functions as a stock scanner. This page will retrieve data from an external API using default parameters, while also offering users the ability to customize parameters and re-run the scan to display the resu ...

Can you explain the rule known as the "next-line" in TypeScript?

No code examples are available for the specific scenario described below: "next-line": [ true, "check-catch", "check-finally", "check-else", "check-open-brace", "check-whitespace" ], ...

Is it possible to invoke a component's function within the click function of a Chartjs chart?

How do I trigger a function in my Component from an onclick event in my chart.js? export class ReportesComponent implements OnInit { constructor(public _router: Router, private data: ReporteService) {} this.chart = new Chart('myChart', { ...

Data fetched by Next.js is failing to display on the web page

After writing a fetch command, I was able to see the data in the console.log but for some reason it is not showing up in the DOM. export default async function links(){ const res = await fetch('https://randomuser.me/api/'); const data = ...

Angular 2 wrap-up: How to seamlessly transfer filter data from Filter Component to App Component

A filtering app has been created successfully, but there is a desire to separate the filtering functionality into its own component (filtering.component.ts) and pass the selected values back to the listing component (app.ts) using @Input and @Output functi ...

Using TypeScript to define callback functions within the Cordova.exec method

I'm encountering an issue with the TypeScript definition for Cordova. The codrova.d.ts file doesn't allow for any function arguments in the success-callback and error-callback. To better illustrate my problem, here's a small example: Here ...

List of nested objects converted into a flat array of objects

Looking to transform a data structure from an array of objects containing objects to an objects in array setup using JavaScript/Typescript. Input: [ { "a": "Content A", "b": { "1": "Content ...

Can Typescript restrict a value to only exist within a specified set of key names within the same object?

I am completely new to Typescript and I am fascinated by the way it can check types. One thing I would like to know is if Typescript can be used to verify at compile time whether a value's domain falls within a predefined set of key names that are de ...

What advantages does subscribe() offer compared to map() in Angular?

I recently started exploring observables in angular2 and found myself puzzled over the decision to use map() instead of subscribe(). Let's say I am fetching data from a webApi, like so: this.http.get('http://172.17.40.41:8089/api/Master/GetAll ...

Using TypeScript to efficiently filter an Array by converting all values to lowercase

I have a custom array in TypeScript that needs to be filtered based on the city and job, with case-insensitivity as a requirement. array = [{ name: "Hardik", city: null, job: null }, { name: "John", city: "Ahmedabad", job: "IT" }, { name: "Margie", c ...

Consider the presence of various peer dependency versions in a react-typescript library

Currently, I am in the process of converting my react component library react-esri-leaflet to typescript. This library requires the user to install react-leaflet as a peerDependency and offers support for both react-leaflet version 3 (RLV3) and react-leafl ...

Which option is more beneficial for intercepting API data in Angular 6: interfaces or classes?

My API returns JSON data that is not structured the way I need it, so I have to make changes. { "@odata.context":"xxxxxx", "id":"xxxxxxxx", "businessPhones":[ ], "displayName":"name", "givenName":"pseudo", "jobTitle":null, "ma ...