question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

Using react hooks inside selector (useHistory)

See original GitHub issue

Hi,

We use an atom and a selector for providing a custom fetchWithAuth which automatically sends an authentication token for every request:

export const authTokenState = atom({
  key: 'authTokenState',
  default: '',
});

const fetchWithCredentials = async (
  input: RequestInfo,
  init?: RequestInit,
  token?: string,
) => {
  const response = await fetch(input, {
    method: 'GET',
    credentials: 'include',
    ...init,
    headers: {
      pragma: 'no-cache',
      'cache-control': 'no-cache',
      Accept: 'application/json, text/plain, */*',
      ...(token ? { Authorization: token } : null),
      ...(init ? init.headers : null),
    },
  });

  const { status } = response;
  // history previously from useHistory
  //if (status === 401) history.replace(loginUrl);
  return response;
};

export const fetchWithAuth = selector({
  key: 'fetchWithAuthState',
  get: ({ get }) => {
    const authToken = get(authTokenState);
    return (input: RequestInfo, init?: RequestInit) =>
      fetchWithCredentials(input, init, authToken);
  },
});

Previously, the fetchWithAuth has been provided by a custom hook, which used the useHistory hook to add the redirect in case of a 401.

I could add the history as a parameter and could use selectorFamily instead but then every consumer would have to provide the history every time it wants to use the custom fetchWithAuth function.

Now my question is: How can I access the history inside the selector properly?

Maybe I’m using it all in the completely wrong way, I’m at the beginning of digging into Recoil. Therefore, any suggestions are welcome.

Issue Analytics

  • State:closed
  • Created 3 years ago
  • Comments:13

github_iconTop GitHub Comments

4reactions
eLeontevcommented, Jul 20, 2020

casting could help:

const historyState = atom({ key: 'history', default: null as unknown as History})
// or
const historyState = atom<History>({ key: 'history', default: null as any})
3reactions
tklepzigcommented, Jul 21, 2020

I learned that RecoilRoot can be used with an initial state, so I tried the following:

	const historyState = atom({ key: 'history', default: null });
	
	const App = () => {
	  	const history = useHistory();
	
	  	return <RecoilRoot initializeState={({ set }) => { set(historyState, history); }}>
	  		...
		</RecoilRoot>
	}

It seems to work, on the very first render the history is already set. Are there any possible drawbacks using this approach?

Read more comments on GitHub >

github_iconTop Results From Across the Web

React's useHistory and Redirect hooks - DEV Community ‍ ‍
This tutorial is based on exploring the useHistory hook of react-router-dom which is a special package of react that allows us to make...
Read more >
Navigating your React app with the useHistory hook
The useHistory hook ships with React Router and lets us access the state of the router to navigate from inside our components. Hooks...
Read more >
How to use React's useHistory() hook - Felix Gerschau
The useHistory hook allows us to access React Router's history object. Through the history object, we can access and manipulate the current ...
Read more >
How to test React component that uses React Hooks ...
The problem here comes from inside of useHistory hook as you can imagine. The hook is designed to be used in consumers of...
Read more >
useHooks - Easy to understand React Hook recipes
If you use React Router you might have noticed they recently added a number of useful hooks, specifically useParams , useLocation , useHistory...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found