Problem with wrapping whole React App (all pages) in certain functionality - reactjs

I have React App consisting of few pages. LandingPage (to be clear, it is really the first page in app flow)is like this:
export const LocalLandingPage = () => {
const { Favorites } = useFavorites();
React.useEffect(() => {
Favorites.manageSupport() && Favorites.showSize();
}, []);
return (...here goes actual content...);
};
const LandingPage = withRouter(wrappedInLinkToSearchHOC(WithSnackBarHOC(LocalLandingPage)));
Here I call hook useFavorites which gathers some methods dealing with a specific subset of local Storage content(and dispatches actions to Redux store as well). The code above return call is checks support for local Storage and tells if some specific items are stored and in what quantity.
The story is that I have realized that if someone enters not the LandingPage but any other page of the app, the code will not be executed and support for localStorage not checked.
Besides, it is really not LandingPage business to deal with storage, so it should be removed anywhere.
My idea was to write HOC and wrap the application. So, here is this HOC (to keep things simple it is initially JS not TS) To make useFavorites work, it had to be a hook, too.
import useFavorites from '../hooks/useFavorites';
const useCheckSupportForLocalStorage = Component => {
const { Favorites } = useFavorites();
// React.useEffect(() => {
Favorites.manageSupport() && Favorites.showSize();
// }, []);
return props => <Component {...props} />;
};
export default useCheckSupportForLocalStorage;
Having it done, I have tried to use it on App like this
function App() {
return (
<Switch>
... here are routes...
</Switch>
);
}
export default useCheckSupportForLocalStorage(App);
It throws an error:
React Hook "useCheckSupportForLocalStorage" cannot be called at the top level.
That is truth, no doubt. So, the next idea was to create a temporary component from all routes.
function Routes() {
const Routes = useCheckSupportForLocalStorage(
<>
<Route exact path={Paths.landing} component={Awaiting(StarWars)} />
...here is the rest or outes...
</>,
);
return <Routes />;
}
export default Routes;
And use it in rewritten App like this
function App() {
return (
<Switch>
<Routes />
</Switch>
);
}
but it throws error
Routes' cannot be used as a JSX component.
Its return type '(props: any) => Element' is not a valid JSX element.
Type '(props: any) => Element' is missing the following properties from type 'ReactElement<any, any>': type, props, key
Forcing useCheckSupportForLocalStorage th have return type of ReactElement doesn't help, just leads to other error. I have checked few others options as well. What is wrong, how should it be written?
Basically I could stop using useFavorites in this hook, then it would be just a function - but it would be extreme headache.

You say
To make useFavorites work, it had to be a hook, too.
That is not true, since you have it in a component it will work just fine. And my understanding is that you want to wrap your whole app with it, so no need for the HOC. Just use it at the top of your app hierarchy.
something like
import useFavorites from '../hooks/useFavorites';
const CheckSupportForLocalStorage = ({ children }) => {
const { Favorites } = useFavorites();
React.useEffect(() => {
Favorites.manageSupport() && Favorites.showSize();
}, []);
return children;
};
export default CheckSupportForLocalStorage;
and
function App() {
return (
<CheckSupportForLocalStorage>
<Switch>
... here are routes...
</Switch>
</CheckSupportForLocalStorage>
);
}
export default App;

Related

Definig page component only by HOC in NextJS

I have nextjs (react) website I use (on every "page") same template - there is Detail and List component.
I have definition of every page as XML (not nextjs thing but my implementation). Root element here is Forms and childrens are individual form defined like this:
<Form FID="Event">
<DetailFrame createNewEntryText="Add event">
<Component attributeKey="img_url" componentName="chose file" componentType="FileChooser" path="img/albums/other/event-photos/#[img_url]"/>
<Component attributeKey="title" componentName="Title" componentType="TextField" transformation="#[title]"/>
<Component attributeKey="date" componentName="Date" componentType="DateField" transformation="#[date]"/>
<Component attributeKey="description" componentName="Description" componentType="RichTextField" transformation="#[description]"/>
</DetailFrame>
<ListFrame orderBy="date" descending="true">
<Component attributeKey="id_event" componentName="ID" componentType="TextField" transformation="#[id_event]"/>
<Component attributeKey="img_url" componentName="Image preview" componentType="ImagePreview" transformation="img/albums/other/event-photos/#[img_url]" />
<Component attributeKey="title" componentName="Title" componentType="TextField" transformation="#[title]"/>
<Component attributeKey="date" componentName="Date" componentType="DateField" transformation="#[date]"/>
<Component attributeKey="description" componentName="Description" componentType="RichTextField" transformation="#[description]"/>
</ListFrame>
</Form>
Only thing what I need specify on every nextjs page is FID and individual component will then compose by their own by XML definition of form. All the stuff like menu and other components (except FormFrameContainer which is wrapper for Detail and List components) are defined in _document.tsx (= html wrapper for nextjs pages offered by nextjs) and _app.tsx (= components wrapper for nextjs pages offered by nextjs; wrapped by _document.tsx). To be clear - FormFrameContainer is wrapped by that stuffs in _app.tsx and _document.tsx.
So every administration page look almost same, like this:
const EventsPage: NextPage = (props: any) =>{
const dispatch = useAppDispatch();
useEffect(() => {
dispatch({ type: SagaActions.SET_FORM_DEFINITIONS_AND_SET_FORM_BY_ID, FID: "Event" });
}, [dispatch])
return (
<div>
<FormFrameContainer />
</div>
)
}
Because of repetition I decided to move useeffect logic into hoc named withAdminPage:
export default (Page: NextPage, formID: string) => {
return (props) => {
const dispatch = useAppDispatch();
useEffect(() => {
dispatch({ type: SagaActions.SET_FORM_DEFINITIONS_AND_SET_FORM_BY_ID, FID: formID });
}, [dispatch])
return <Page {...props} />;
}
}
So literaly the only thing what remains in particular pages is returning:
<div>
<FormFrameContainer />
</div>
What comes to my mind is also move it to hoc, because it is also same in all pages => duplication. But it would mean, that I will not actually define components (my hoc will generate them) and in every page file will be only this one line:
export default withAdminPage(EventsPage, "Event");
For me it seems logic but also as some anitpattern to hoc (because hoc is defined as function, that take component and return new (enhanced) component). So? What would be best practise here? Would it be violation of some code standards?

Use swr with Next global context: entire page gets re-rendered

I have the following piece of code:
function MyApp({ Component, pageProps }: AppProps) {
const { tronLinkAuth, tronLinkLoading, mutateTronLink } = useTronLink();
const { authenticatedUser, authLoading, authLoggedOut, mutateAuth } = useAuthenticatedUser();
return (
<React.StrictMode>
<CSSReset />
<ColorModeScript initialColorMode={theme.config.initialColorMode} />
<ChakraProvider theme={theme}>
<AuthenticationContext.Provider value={{
tronLinkAuth, tronLinkLoading, mutateTronLink,
authenticatedUser, authLoading, authLoggedOut, mutateAuth
}}>
<Component {...pageProps} />
</AuthenticationContext.Provider>
</ChakraProvider>
</React.StrictMode>
)
}
Example useAuthenticatedUser:
export default function useAuthenticatedUser() {
const { data, mutate, error } = useSWR("api_user", fetcher, {
errorRetryCount: 0
});
const loading = !data && !error;
const loggedOut = error && error instanceof UnauthorizedException;
return {
authLoading: loading,
authLoggedOut: loggedOut,
authenticatedUser: data as AuthenticatedUser,
mutateAuth: mutate
};
}
The code works, but my entire webpage gets re-rendered when swr propagates its result.
For example:
const Login: NextPage = () => {
console.log('login update');
return (
<>
<Head>
<title>Register / Login</title>
</Head>
<Navbar />
<Box h='100vh'>
<Hero />
</Box>
<Box h='100vh' pt='50px'>
Test second page
</Box>
</>
)
}
export default Login;
When using useContext in the Navbar, it also re-renders the entire LoginPage, including the Hero, while this is not my purpose.
const Navbar: React.FC = () => {
const authState = useContext(AuthenticationContext);
...
I'm also confused as for why the logs appear in the server console, as this is supposed to be executed client-side.
Edit: not an issue, this is only on first render.
How to solve?
I'm interested in using swr for this use case, because it allows me to re-verify the authentication status e.g. on focus but use the cached data meanwhile.
Edit:
Confusing. The following log:
function MyApp({ Component, pageProps }: AppProps) {
console.log('app');
const { tronLinkAuth, tronLinkLoading, mutateTronLink } = useTronLink();
const { authenticatedUser, authLoading, authLoggedOut, mutateAuth } = useAuthenticatedUser();
Also gets printed out every time I switch tabs and activate the swr.
So it re-renders the entire tree? Doesn't seem desirable...
I currently went with the easier solution, i.e. use useSwr immediately on the component that uses the data.
From the docs:
Each component has a useSWR hook inside. Since they have the
same SWR key and are rendered at the almost same time, only 1 network
request will be made.
You can reuse your data hooks (like useUser in the example above)
everywhere, without worrying about performance or duplicated requests.
So it can be leveraged to re-use it wherever needed without having to worry about global state re-renders.
In case there is an alternative response how to use the global Context Provider, don't hesitate to share.

Using Persistent Layouts in NextJS with Higher Order Functions

Im using Adam Wathan's method for using persistent layouts in Next. Is there a way to get them to work with Higher Order Functions? I'm not really sure how HOFs work.
My _app.js
function MyApp({ Component, pageProps }) {
const Layout = Component.layout || (children => <>{children}</>)
return (
<Layout>
<Component {...pageProps} />
</Layout>
)
}
A sample page looks like this
const Home = () => {
return (
<>
...
</>
)
}
Home.Layout = BaseLayout;
export const getServerSideProps = withAuthUserTokenSSR()()
export default withAuthUser()(Home)
If I remove the HOF the layouts work fine, otherwise I get:
Error: Objects are not valid as a React child (found: object with keys {children}). If you meant to render a collection of children, use an array instead.
You need to apply the layout component to the higher-order component itself, as it's probably wrapping your original Home component and hiding Home.layout away.
const Home = () => {
return (
<></>
)
}
const HomeWithAuth = withAuthUser()(Home)
HomeWithAuth.layout = BaseLayout;
export default HomeWithAuth
Also, make sure you use the same variable name (same casing, e.g., layout vs. Layout) in your page component and when you refer to it in _app.

Testing that a React Component correctly reads and renders a path parameter

I have the React/Typescript component below. It works as expected, but I'm trying to prove that with a test (using testing-library). I want to ensure that it correctly receives the level parameter and renders it to the page:
import React from "react";
import { useParams } from "react-router-dom";
type QuestionGridParams = {
level: string;
};
export const QuestionGrid = () => {
const { level } = useParams<QuestionGridParams>();
return (
<>
<header>
<h1>Level {level}</h1>
</header>
</>
);
};
I'd expected to do this by stubbing the context, or the function that returns the context, so that it always returns a specified value for the parameter. None of my searching has given a solution that I can get to work. Closest I have come is the test below, which only proves that the component works if no parameter is passed in. I want to pass in a level of 4, for example, and assert that there is an element with the text Level 4.
I don't think that this is the approach I need, it just happens to be the only way for now I can get the test not to error when useParams() is invoked..
test("page renders in the absence of a 'level' parameter", () => {
const layout = render(
<Router history={createMemoryHistory()}>
<QuestionGrid/>
</Router>
);
const header: any = layout.getByText("Level");
expect(header).toBeInTheDocument();
});
Any help getting past this mindblock would be greatly appreciated.
OK, so this worked:
test("page reads and renders the 'level' path parameter ", () => {
const layout = render(
<Router history={createMemoryHistory()}>
<Route path={"/:level"}>
<QuestionGrid/>
</Route>
</Router>
);
history.push("/4");
const header: any = layout.getByText("Level 4");
expect(header).toBeInTheDocument();
});
or more elegantly
test("page reads and renders the 'level' path parameter ", () => {
const layout = render(
<MemoryRouter initialEntries={["/4"]}>
<Route path={"/:level"}>
<QuestionGrid/>
</Route>
</MemoryRouter>
);
const header: any = layout.getByText("Level 4");
expect(header).toBeInTheDocument();
});
No stubbing/mocking, just dynamically creating a real route. Welcome to React, me!
Thanks #jonrsharpe and #r3wt

Custom Admin component with custom dataprovider

I need custom Admin component to update the list of Resource components dynamically.
The documentation provides an example:
import * as React from 'react';
import { useEffect, useState } from 'react';
import { AdminContext, AdminUI, Resource, ListGuesser, useDataProvider } from 'react-admin';
function App() {
return (
<AdminContext dataProvider={myDataProvider}>
<AsyncResources />
</AdminContext>
);
}
function AsyncResources() {
const [resources, setResources] = useState([]);
const dataProvider = useDataProvider();
useEffect(() => {
// Note that the `getResources` is not provided by react-admin. You have to implement your own custom verb.
dataProvider.getResources().then(r => setResources(r));
}, []);
return (
<AdminUI>
{resources.map(resource => (
<Resource name={resource.name} key={resource.key} list={ListGuesser} />
))}
</AdminUI>
);
}
It is supposed to work with custom dataprovider that has getResources() function.
Ok. But how this function is supposed to look like? Or rather what it should return? Because tried many things and none is flying.
And also. There is a warning about React Hook useEffect missing a dependency: 'dataProvider'. Solutions online aren't usable so far. I don't think my example doesn't work because of that, but it's possible. How to fix that in that case?
So yeah, in short - how to make this provided in documentation example to work?
+++
Edit: In case anyone wondering here is how I apply my dataprovider:
import dataProvider from './dataprovider';
function App() {
return (
<AdminContext dataProvider={dataProvider}>
<AsyncResources />
</AdminContext>
);
}
And here is my get_resources function:
getResources: () => {
const url = `${apiUrl}/get_resources`;
return httpClient(url).then(
({ headers, json }) => ({
data: json["data"],
total: json["total"]
}));
},
Edit 2:
Problem maybe lies within dataprovider, since it fails with error message "TypeError: can't convert undefined to object" while trying to call "isDataProviderOptions" function from here: node_modules/ra-core/esm/dataProvider/getDataProviderCallArguments.js:19.
Or it's calling the wrong dataprovider. Not the custom one I've supplied to the AdminContext component.
Should I add the code of my custom dataprovider?

Resources