Skip to content

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We鈥檒l occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to reload a next auth session while using react-query #4275

Closed
DBankx opened this issue Mar 28, 2022 · 0 comments
Closed

How to reload a next auth session while using react-query #4275

DBankx opened this issue Mar 28, 2022 · 0 comments
Labels
question Ask how to do something or how something works

Comments

@DBankx
Copy link

DBankx commented Mar 28, 2022

Question 馃挰

Hi, i am new to both next JS and react query and i have been cracking my head wondering how to reload session when using nextJS to populate session data with new data from backend for almost a week now.

Sceneario: User updates profile
current behaviour: User has to logout and login to get the new data persisted to the session
Expected Results: Session query key gets updated with new session and with the data the user inputed previously

Tools used: Next.js, Next-auth, react-query

Code:
This is the code we are currently running in our application

_app.js

function MyApp({ Component, pageProps }) {
  const [showBottomNav, setShowBottomNav] = useState(true);
  const [queryClient] = useState(
    () =>
      new QueryClient({
        defaultOptions: {
          queries: {
            staleTime: 60 * 1000 * 60 * 0.3
          }
        }
      })
  );
  return (
    <ThemeProvider attribute='class'>
      <QueryClientProvider client={queryClient}>
        <Hydrate state={pageProps.dehydratedState}>
          <AppContext.Provider
            value={{
              state: {
                showBottomNav
              },
              setShowBottomNav
            }}
          >
            {/* <SessionProvider session={pageProps.session}> */}
            <ToastContainer position='top-center' autoClose={5000} pauseOnHover hideProgressBar icon={false} />
            <Component {...pageProps} />
            {/* </SessionProvider> */}
            <ReactQueryDevtools initialIsOpen={false} />
          </AppContext.Provider>
        </Hydrate>
      </QueryClientProvider>
    </ThemeProvider>
  );
}

useQuerySession.js
This is where we make a call to the api to get the session and store it as a query

export async function fetchSession() {
  const res = await fetch('/api/auth/session');
  const session = await res.json();
  if (Object.keys(session).length) {
    return session;
  }
  return null;
}

export function useQuerySession({ required, redirectTo = '/login', queryConfig = {} } = {}) {
  const router = useRouter();
  const query = useQuery(['session'], fetchSession, {
    ...queryConfig,
    onSettled(data, error) {
      if (queryConfig.onSettled) queryConfig.onSettled(data, error);
      if (data || !required) return;
      router.push(redirectTo);
    }
  });
  return [query.data, query.status === 'loading'];
}

We have previously gone through the issues to see if there's a way to do this and we came across this reload session function
session.js

export const reloadSession = () => {
  const event = new Event('visibilitychange');
  document.dispatchEvent(event);
};

we have tried using this function and the session does not get updated with the new data. we think it is because we chose to use react-query and not include the session provider component in our _app.js

So the $64000 question is. how can i get to reload my session so if a user updates a profile my session updates too without having to prompt the user to logout and login again using react-query. is there any function we could call or anything we could use.

Thank you.

How to reproduce 鈽曪笍

attempt to use react-query with next js

Contributing 馃檶馃徑

Yes, I am willing to help answer this question in a PR

@DBankx DBankx added the question Ask how to do something or how something works label Mar 28, 2022
@nextauthjs nextauthjs locked and limited conversation to collaborators Mar 31, 2022
@balazsorban44 balazsorban44 converted this issue into discussion #4297 Mar 31, 2022

This issue was moved to a discussion.

You can continue the conversation there. Go to discussion →

Labels
question Ask how to do something or how something works
Projects
None yet
Development

No branches or pull requests

1 participant