Bhardwaj Avasarala
Bhardwaj Avasarala

Reputation: 63

How to define functions in Child Context Provider from Parent Context Provider in React?

I'm new to react and I'm facing issue in the Context API using

React Functional Components

For example I have a scenario where I need to split the authentication providers based on the host since all of them have different way of authentication logic.

I have following child providers:

i. ChildHostProviderA

ii. ChildHostProviderB

iii. ChildHostProviderC

iv. ChildHostProviderD

I need to switch the authentication providers from the parent provider based on where the application is.

What I have done is created a generic Context Provider (ParentHostProvider) which will be switched based on the host it is in. The generic context provider will have these functions:

  1. GetAccessToken()
  2. SignIn()
  3. SingOut()

If I need these functions to be implemented in the Child Providers then what is the best way to do in React?

I've tried finding many resources online but couldn't find one, any help regarding this scenario would be really helpful.

Upvotes: 0

Views: 450

Answers (1)

abumalick
abumalick

Reputation: 2346

If I understand correctly, the app is deployed on different hosts and the authentication logic changes according to the host.

If it is the case, you don't need to involve context in this logic, as it will never change for a host. It is more related to Javascript than React.

You can create a file called authenticationFunctions.js with all your different functions logic organized by hostname. Like this:

export default {
  "host1.dev": {
    getAccessToken: () => {
      console.log("host1 get access token");
    },
    signIn: () => {
      console.log("host1 sign in");
    },
    signOut: () => {
      console.log("host1 sign out");
    }
  },
  "759ee.codesandbox.io": {
    getAccessToken: () => {
      console.log("codesandbox.io get access token");
    },
    signIn: () => {
      console.log("codesandbox.io sign in");
    },
    signOut: () => {
      console.log("codesandbox.io sign out");
    }
  }
};

And after that in your provider you will select the correct functions according to the hostname and pass it to the provider

import React, { useContext } from "react";
import authenticationFunctions from "./authenticationFunctions";
const UserContext = React.createContext(null);

const hostname = window.location.hostname;
let funs = authenticationFunctions[hostname];
if (!funs) {
  console.error("There is no authenticationFunctions for this host");
}

export default function UserProvider({ children }) {
  return (
    <UserContext.Provider value={funs || {}}>{children}</UserContext.Provider>
  );
}

Here is a Codesandbox demonstrating this: https://codesandbox.io/s/authentication-logic-change-according-to-host-759ee?file=/src/UserProvider.js:156-329

Upvotes: 1

Related Questions