Changing the EndPoint and Search Key post authentication

Hi, we are using Proxy for the appSearch and wondering, how to change the endPoint and searchKey once the user is authenticated. I'm using useEffect and dynamically changing the endPoint and searchKey if the user is authenticated. But the appSearch keeps taking only the endpoint and searchKey with the initialized ones.

Here is my code.

const [accessToken, setAccessToken] = useState([])
const connector = new AppSearchAPIConnector({
    searchKey: accessToken != 'undefined'&&accessToken.length>0 ? `Bearer ${accessToken}` : `${search_key}`,
    endpointBase: public_url });

const [config,setConfig] = useState({
    apiConnector: connector,
    autocompleteQuery: {.....

  useEffect(() => {
              const secureConnector = new AppSearchAPIConnector({
                searchKey: `Bearer ${accessTokenFromServer}`,
                endpointBase: auth_url
              setConfig({...config,apiConnector: secureConnector})

Everything will need to be completely re-initialized.

A practical way to do this in React is to force your component tree to remount from as high in your component tree as possible.

For instance, if all of the code you posted is contained in an "App" component, you could use a "key" prop to force it to re-mount every time that "accessToken" changes.

<App key={accessToken} accessToken={accessToken} />

Reference: Forcing state reset on a React component by using the key prop | by Alberto Gasparin | Medium

Thanks Jason. I did like you said, i've added the key to 'SearchProvider' as below

const [access_Token, setAccessToken] = useState('')
<SearchProvider config={config} key={access_Token} accessToken={access_Token}>

i still see it is using the old values even though i could see the key got updated in the components section. anyway to clear the cache it might be using?

Try wrapping the SearchProvider in another component, and use the key on the wrapper.

Thanks Jason. I've created the wrapper and still didn't work. I found out that the order of updating was incorrect and hence it is not being reflected. i've changed the order in the useEffect and now it is working correctly as expected. Thanks a lot for your help.

This topic was automatically closed 28 days after the last reply. New replies are no longer allowed.