Skip to content

Commit

Permalink
fix user state not updating on login/logout (#1225)
Browse files Browse the repository at this point in the history
  • Loading branch information
mipyykko authored Aug 18, 2023
1 parent 84cd67d commit 1610cc4
Show file tree
Hide file tree
Showing 14 changed files with 59 additions and 48 deletions.
3 changes: 3 additions & 0 deletions frontend/components/Dashboard/CourseCard.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -239,6 +239,7 @@ const CourseCard = ({ course, loading, isNew }: CourseCardProps) => {
<>
<StyledButton
href={`/courses/${course.slug}`}
prefetch={false}
aria-label={t("courseToCoursePage", { name: course.name })}
variant="text"
startIcon={<DashboardIcon />}
Expand All @@ -247,6 +248,7 @@ const CourseCard = ({ course, loading, isNew }: CourseCardProps) => {
</StyledButton>
<StyledButton
href={`/courses/new?clone=${course.slug}`}
prefetch={false}
aria-label={t("courseCloneCourse", { name: course.name })}
variant="text"
color="secondary"
Expand All @@ -267,6 +269,7 @@ const CourseCard = ({ course, loading, isNew }: CourseCardProps) => {
)}
{isNew && (
<StyledButton
prefetch={false}
href={`/courses/new`}
aria-label={t("courseNewCourse")}
variant="text"
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -95,6 +95,7 @@ const courseEditSchema = ({ client, initialSlug, t }: CourseEditSchemaArgs) => {
.required(t("courseTeacherEmailRequired")),
support_email: Yup.string().email(t("courseEmailInvalid")),
start_date: Yup.mixed<DateTime>()
.nullable()
.typeError(t("courseStartDateRequired"))
.required(t("courseStartDateRequired"))
.transform((datetime?: string | DateTime) => {
Expand Down Expand Up @@ -124,6 +125,7 @@ const courseEditSchema = ({ client, initialSlug, t }: CourseEditSchemaArgs) => {
},
),
end_date: Yup.mixed<DateTime>()
.nullable()
.test(
"end_invalid",
t("invalidDate"),
Expand Down Expand Up @@ -234,9 +236,10 @@ const courseEditSchema = ({ client, initialSlug, t }: CourseEditSchemaArgs) => {
})
}

export type CourseEditSchemaType = Yup.InferType<
ReturnType<typeof courseEditSchema>
>
export type CourseEditSchemaType = Omit<
Yup.InferType<ReturnType<typeof courseEditSchema>>,
"start_date"
> & { start_date: DateTime | null } // help typescript a bit, even if we don't really allow null

interface ValidateSlugArgs {
client: ApolloClient<object>
Expand Down
5 changes: 2 additions & 3 deletions frontend/components/Dashboard/Editor/Course/serialization.ts
Original file line number Diff line number Diff line change
Expand Up @@ -45,9 +45,8 @@ export const toCourseForm = ({
]),
language: course.language ?? "",
support_email: course.support_email ?? "",
// @ts-expect-error: expected to be invalid initially
start_date: course.start_date ? DateTime.fromISO(course.start_date) : "",
end_date: course.end_date ? DateTime.fromISO(course.end_date) : undefined,
start_date: course.start_date ? DateTime.fromISO(course.start_date) : null,
end_date: course.end_date ? DateTime.fromISO(course.end_date) : null,
start_point: course.start_point ?? false,
promote: course.promote ?? false,
hidden: course.hidden ?? false,
Expand Down
4 changes: 2 additions & 2 deletions frontend/components/Dashboard/Editor/Course/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,8 +18,8 @@ export interface CourseFormValues extends FormValues {
teacher_in_charge_name: string
teacher_in_charge_email: string
support_email?: string
start_date: DateTime
end_date?: DateTime
start_date: DateTime | null
end_date: DateTime | null
ects?: string
photo?: string | ImageCoreFieldsFragment | null
language?: string
Expand Down
22 changes: 19 additions & 3 deletions frontend/components/Dashboard/Users/Search/SearchForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,8 @@ import {
useState,
} from "react"

import dynamic from "next/dynamic"

import KeyboardArrowDownIcon from "@mui/icons-material/KeyboardArrowDown"
import KeyboardArrowUpIcon from "@mui/icons-material/KeyboardArrowUp"
import {
Expand All @@ -20,17 +22,31 @@ import { styled } from "@mui/material/styles"
import { useEventCallback } from "@mui/material/utils"

import { Column, Row } from "./Common"
import MobileGrid from "./MobileGrid"
import { SearchFieldOptions } from "./SearchFieldOptions"
import { MetaResult, NarrowMetaResult } from "./SearchMetaResult"
import WideGrid from "./WideGrid"
import { ButtonWithPaddingAndMargin } from "/components/Buttons/ButtonWithPaddingAndMargin"
import { H1NoBackground } from "/components/Text/headers"
import UserSearchContext from "/contexts/UserSearchContext"
import { useTranslator } from "/hooks/useTranslator"
import UsersTranslations from "/translations/users"
import { isDefinedAndNotEmpty } from "/util/guards"

const MobileGrid = dynamic(() => import("./MobileGrid"), {
ssr: false,
loading: () => null,
})
const WideGrid = dynamic(() => import("./WideGrid"), {
ssr: false,
loading: () => null,
})
const MetaResult = dynamic(
() => import("./SearchMetaResult").then((c) => c.MetaResult),
{ ssr: false, loading: () => null },
)
const NarrowMetaResult = dynamic(
() => import("./SearchMetaResult").then((c) => c.NarrowMetaResult),
{ ssr: false, loading: () => null },
)

const StyledForm = styled("form")`
display: flex;
flex-direction: column;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -82,11 +82,8 @@ export function CourseEntry({ children }: PropsWithChildren) {
key={`${selectedData.course.id}-progress`}
data={selectedData}
/>
<TotalProgressEntry /*data={selectedData.user_course_progress.extra}*/
/>
<TierExerciseList
/*data={selectedData.user_course_progress?.extra.exercises}*/
/>
<TotalProgressEntry />
<TierExerciseList />
</>
)}
</>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,18 +26,7 @@ function UserPointsSummary() {
return (
<UserPointsSummaryContainer>
{!isNarrow && <CourseSelectList />}
{loading || state.loading ? (
<CourseEntrySkeleton />
) : (
/*data?.length === 0 ? (
<Typography variant="h3" margin="0.5rem" p="0.5rem">
{t("noResults")}
</Typography>
) : */ <CourseEntry />
)}
{/*filteredData.map((entry, index) => (
<CourseEntry key={entry.course?.id ?? index} data={entry} />
))*/}
{loading || state.loading ? <CourseEntrySkeleton /> : <CourseEntry />}
</UserPointsSummaryContainer>
)
}
Expand Down
2 changes: 1 addition & 1 deletion frontend/components/Link.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -7,5 +7,5 @@ export const LinkBehavior = React.forwardRef<
React.AnchorHTMLAttributes<HTMLAnchorElement> & NextLinkProps
>((props, ref) => {
const { href, ...other } = props
return <NextLink ref={ref} href={href} prefetch={false} {...other} />
return <NextLink ref={ref} href={href} {...other} />
})
12 changes: 6 additions & 6 deletions frontend/components/SignInForm.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -96,12 +96,12 @@ function SignIn() {
// TODO: typing
e.preventDefault()
try {
await signIn(
{ email, password, shallow: false },
apollo,
logInOrOut,
)

await signIn({ email, password, shallow: false }, apollo)
try {
await logInOrOut()
} catch (e) {
console.error("Login in or out failed")
}
if (errorTimeout) {
clearTimeout(errorTimeout)
}
Expand Down
5 changes: 2 additions & 3 deletions frontend/lib/authentication.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,12 +38,12 @@ export const signIn = async (
const res = await tmcClient.authenticate({ username: email, password })
const details = await userDetails(res.accessToken)

await apollo?.resetStore()

document.cookie = `access_token=${res.accessToken};path=/`

document.cookie = `admin=${details.administrator};path=/`

await apollo?.resetStore()

cb?.()

const rawRedirectLocation = nookies.get()["redirect-back"]
Expand Down Expand Up @@ -85,7 +85,6 @@ export const signOut = async (
setTimeout(() => {
cb()
setTimeout(() => {
apollo.stop()
apollo.resetStore()
}, 100)
}, 100)
Expand Down
2 changes: 1 addition & 1 deletion frontend/lib/with-apollo-client/get-apollo.ts
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ export default function getApollo(
previousAccessToken = accessToken
previousLocale = locale

if (initialState) {
if (initialState && isBrowser) {
const existingCache = _apolloClient.extract()
const data = deepmerge(existingCache, initialState, {
arrayMerge: (destination: any, source: any) => [
Expand Down
6 changes: 2 additions & 4 deletions frontend/lib/with-apollo-client/index.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -32,7 +32,7 @@ const withApolloClient = (App: any) => {
// eslint-disable-next-line react-hooks/rules-of-hooks
const router = useRouter()
const locale = router.locale ?? pageProps?.router?.locale
const apolloClient = apollo ?? getApollo(apolloState, accessToken, locale)
const apolloClient = getApollo(apolloState, accessToken, locale)

return (
<ApolloProvider client={apolloClient}>
Expand Down Expand Up @@ -76,6 +76,7 @@ const withApolloClient = (App: any) => {
}

pageProps.pageProps.currentUser = currentUser

if (typeof window === "undefined") {
if (ctx?.res?.headersSent || ctx?.res?.finished) {
return pageProps ?? {}
Expand All @@ -93,9 +94,6 @@ const withApolloClient = (App: any) => {
renderFunction: renderToString,
tree: <AppTree {...appTreeProps} Component={Component} />,
})
/*const rendered = await renderToStringWithData(
<AppTree {...appTreeProps} Component={Component} />
)*/
// Run all GraphQL queries
} catch (error) {
// Prevent Apollo Client GraphQL errors from crashing SSR.
Expand Down
9 changes: 5 additions & 4 deletions frontend/pages/_app.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -126,16 +126,17 @@ MyApp.getInitialProps = async (props: AppContext) => {
const admin = signedIn && isAdmin(ctx)
const accessToken = getAccessToken(ctx)

Object.assign(originalProps.pageProps, { signedIn, admin, accessToken })
return originalProps
/*return {
/*Object.assign(originalProps.pageProps, { signedIn, admin, accessToken })
return originalProps*/
return {
...originalProps,
pageProps: {
...originalProps.pageProps,
signedIn,
admin,
accessToken,
},
}*/
}
}

// @ts-ignore: silence for now
Expand Down
8 changes: 7 additions & 1 deletion frontend/pages/_document.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -10,8 +10,14 @@ import originalTheme, {
fontVariableClass as originalFontVariableClass,
} from "/src/theme"

function CustomDocument(props: DocumentProps) {
interface CustomDocumentProps extends DocumentProps {
apolloState: any
}

function CustomDocument(props: CustomDocumentProps) {
props.__NEXT_DATA__.props.apolloState = props.apolloState
const isNew = props.__NEXT_DATA__.page.includes("_new")

const theme = isNew ? newTheme : originalTheme
const fontVariableClass = isNew
? newFontVariableClass
Expand Down

0 comments on commit 1610cc4

Please sign in to comment.