Skip to content

Commit

Permalink
fix(chore): replace use-context-selector context with React Context (#…
Browse files Browse the repository at this point in the history
…20287)

* fix(chore): replace use-context-selector context with React Context

* fix(chore): remove the selector

* fix(chore): remove use-context-selector

* fix(chore): fix prettier issue
  • Loading branch information
simotae14 committed May 21, 2024
1 parent 48a7b1e commit 0c9f2e7
Show file tree
Hide file tree
Showing 17 changed files with 26 additions and 45 deletions.
2 changes: 1 addition & 1 deletion docs/docs/docs/01-core/admin/05-features/authentication.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,7 +12,7 @@ However, we now store the token in state along with the user & this can be passe
## Usage

The `useAuth` hook is built on top of a custom `createContext` version which asserts the context is there and throws an error if this is not the case.
Therefore the hook expects a "consumer name" to be passed so a helpful error message can be provided. It is also built using the `use-context-selector` library meaning we can also pass a selector function to the hook to select a specific part of the context.
Therefore the hook expects a "consumer name" to be passed so a helpful error message can be provided. It is also built using the React.Context API meaning we can have back the context from the hook.

```ts
const token = useAuth('App', (state) => state.token); // token will be a string or null
Expand Down
2 changes: 1 addition & 1 deletion packages/core/admin/admin/src/App.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,7 @@ export const App = ({ authLogo, menuLogo, showReleaseNotification, showTutorials
const { formatMessage } = useIntl();
const dispatch = useDispatch();
const appInfo = useAppInfo();
const token = useAuth('App', (state) => state.token);
const { token } = useAuth('App');

const authRoutes = React.useMemo(() => {
if (!routes) {
Expand Down
5 changes: 3 additions & 2 deletions packages/core/admin/admin/src/components/AuthenticatedApp.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,8 @@ const strapiVersion = packageJSON.version;

const AuthenticatedApp = () => {
const { setGuidedTourVisibility } = useGuidedTour();
const userInfo = useAuth('AuthenticatedApp', (state) => state.user);
const { user } = useAuth('AuthenticatedApp');
const userInfo = user;
const [userDisplayName, setUserDisplayName] = React.useState<string>(() =>
userInfo ? userInfo.username || getFullName(userInfo.firstname ?? '', userInfo.lastname) : ''
);
Expand Down Expand Up @@ -76,7 +77,7 @@ const AuthenticatedApp = () => {
}
}, [showReleaseNotification]);

const userRoles = useAuth('AuthenticatedApp', (state) => state.user?.roles);
const userRoles = user?.roles;

React.useEffect(() => {
if (userRoles) {
Expand Down
18 changes: 7 additions & 11 deletions packages/core/admin/admin/src/components/Context.tsx
Original file line number Diff line number Diff line change
@@ -1,12 +1,10 @@
import * as React from 'react';

import * as ContextSelector from 'use-context-selector';

function createContext<ContextValueType extends object | null>(
rootComponentName: string,
defaultContext?: ContextValueType
) {
const Context = ContextSelector.createContext<ContextValueType | undefined>(defaultContext);
const Context = React.createContext<ContextValueType | undefined>(defaultContext);

const Provider = (props: ContextValueType & { children: React.ReactNode }) => {
const { children, ...context } = props;
Expand All @@ -16,15 +14,13 @@ function createContext<ContextValueType extends object | null>(
return <Context.Provider value={value}>{children}</Context.Provider>;
};

const useContext = <Selected,>(
consumerName: string,
selector: (value: ContextValueType) => Selected
): Selected =>
ContextSelector.useContextSelector(Context, (ctx) => {
if (ctx) return selector(ctx);
// it's a required context.
const useContext = (consumerName: string) => {
const ctx = React.useContext(Context);
if (!ctx) {
throw new Error(`\`${consumerName}\` must be used within \`${rootComponentName}\``);
});
}
return ctx;
};

Provider.displayName = rootComponentName + 'Provider';

Expand Down
2 changes: 1 addition & 1 deletion packages/core/admin/admin/src/components/LeftMenu.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -69,7 +69,7 @@ const LeftMenu = ({ generalSectionLinks, pluginsSectionLinks }: LeftMenuProps) =
const { formatMessage } = useIntl();
const { trackUsage } = useTracking();
const { pathname } = useLocation();
const logout = useAuth('Logout', (state) => state.logout);
const { logout } = useAuth('Logout');

const initials = userDisplayName
.split(' ')
Expand Down
2 changes: 1 addition & 1 deletion packages/core/admin/admin/src/components/NpsSurvey.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -164,7 +164,7 @@ const NpsSurvey = () => {
};
}, []);

const user = useAuth('NpsSurvey', (state) => state.user);
const { user } = useAuth('NpsSurvey');

if (!displaySurvey) {
return null;
Expand Down
2 changes: 1 addition & 1 deletion packages/core/admin/admin/src/components/PrivateRoute.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,7 @@ interface PrivateRouteProps extends Omit<RouteProps, 'render' | 'component'> {
}

const PrivateRoute = ({ children, ...rest }: PrivateRouteProps) => {
const token = useAuth('PrivateRoute', (state) => state.token);
const { token } = useAuth('PrivateRoute');

return (
<Route
Expand Down
2 changes: 1 addition & 1 deletion packages/core/admin/admin/src/features/Configuration.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,7 @@ const ConfigurationProvider = ({
const { formatMessage } = useIntl();
const toggleNotification = useNotification();
const { _unstableFormatAPIError: formatAPIError } = useAPIErrorHandler();
const token = useAuth('ConfigurationProvider', (state) => state.token);
const { token } = useAuth('ConfigurationProvider');

const { data, isSuccess } = useProjectSettingsQuery(undefined, {
skip: !token,
Expand Down
2 changes: 1 addition & 1 deletion packages/core/admin/admin/src/pages/Auth/AuthPage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,7 @@ const AuthPage = ({ hasAdmin }: AuthPageProps) => {
}
);

const token = useAuth('AuthPage', (state) => state.token);
const { token } = useAuth('AuthPage');

if (!authType || !forms) {
return <Redirect to="/" />;
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,7 +40,7 @@ const Login = ({ children }: LoginProps) => {
const query = useQuery();
const { push } = useHistory();

const login = useAuth('Login', (state) => state.login);
const { login } = useAuth('Login');

const handleLogin = async (body: Parameters<typeof login>[0]) => {
setApiError(undefined);
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -144,7 +144,7 @@ const Register = ({ hasAdmin }: RegisterProps) => {

const [registerAdmin] = useRegisterAdminMutation();
const [registerUser] = useRegisterUserMutation();
const setToken = useAuth('Register', (state) => state.setToken);
const { setToken } = useAuth('Register');

const handleRegisterAdmin = async (
{ news, ...body }: RegisterAdmin.Request['body'] & { news: boolean },
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -45,7 +45,7 @@ const ResetPassword = () => {
const query = useQuery();
const { _unstableFormatAPIError: formatAPIError } = useAPIErrorHandler();

const setToken = useAuth('ResetPassword', (state) => state.setToken);
const { setToken } = useAuth('ResetPassword');

const [resetPassword, { error }] = useResetPasswordMutation();

Expand Down
2 changes: 1 addition & 1 deletion packages/core/admin/admin/src/pages/ProfilePage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -81,7 +81,7 @@ const ProfilePage = () => {

useFocusWhenNavigate();

const user = useAuth('ProfilePage', (state) => state.user);
const { user } = useAuth('ProfilePage');

React.useEffect(() => {
if (user) {
Expand Down
5 changes: 4 additions & 1 deletion packages/core/admin/admin/src/pages/UseCasePage.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -77,7 +77,10 @@ export const UseCasePage = () => {
const [role, setRole] = React.useState<string | number | null>(null);
const [otherRole, setOtherRole] = React.useState('');

const { firstname, email } = useAuth('UseCasePage', (state) => state.user) ?? {};
const { user } = useAuth('UseCasePage');
const firstname = user?.firstname;
const email = user?.email;

const { hasAdmin } = parse(location?.search, { ignoreQueryPrefix: true });
const isOther = role === 'other';

Expand Down
2 changes: 1 addition & 1 deletion packages/core/admin/ee/admin/src/pages/AuthResponse.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -23,7 +23,7 @@ const AuthResponse = () => {
);
}, [push, formatMessage]);

const setToken = useAuth('AuthResponse', (state) => state.setToken);
const { setToken } = useAuth('AuthResponse');

React.useEffect(() => {
if (match?.params.authResponse === 'error') {
Expand Down
1 change: 0 additions & 1 deletion packages/core/admin/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -160,7 +160,6 @@
"slate-react": "0.98.3",
"style-loader": "3.3.4",
"typescript": "5.2.2",
"use-context-selector": "1.4.1",
"vite": "5.0.13",
"webpack": "^5.89.0",
"webpack-bundle-analyzer": "^4.10.1",
Expand Down
18 changes: 0 additions & 18 deletions yarn.lock
Original file line number Diff line number Diff line change
Expand Up @@ -7924,7 +7924,6 @@ __metadata:
style-loader: "npm:3.3.4"
styled-components: "npm:5.3.3"
typescript: "npm:5.2.2"
use-context-selector: "npm:1.4.1"
vite: "npm:5.0.13"
webpack: "npm:^5.89.0"
webpack-bundle-analyzer: "npm:^4.10.1"
Expand Down Expand Up @@ -30579,23 +30578,6 @@ __metadata:
languageName: node
linkType: hard

"use-context-selector@npm:1.4.1":
version: 1.4.1
resolution: "use-context-selector@npm:1.4.1"
peerDependencies:
react: ">=16.8.0"
react-dom: "*"
react-native: "*"
scheduler: ">=0.19.0"
peerDependenciesMeta:
react-dom:
optional: true
react-native:
optional: true
checksum: 50e501bc3220ad236f62c251edb8106bc03efa22c3cc6a42b27a4a095e3cbf9fcd5a2ca3ff05aace2015d84cce99cbd32c0ac59d2f1396239dd5fae14a738c3f
languageName: node
linkType: hard

"use-isomorphic-layout-effect@npm:^1.1.2":
version: 1.1.2
resolution: "use-isomorphic-layout-effect@npm:1.1.2"
Expand Down

0 comments on commit 0c9f2e7

Please sign in to comment.