I hope this is a simple question. I can't figure out why it's doing this. Anyways, using NextJS i'm trying to access the params in the router using the useRouter hook and combining it with the querystring plugin to split asPath, since NextJS doesn't allow you to access the query part of the router if using stateless. This is my code:
import { useRouter } from 'next/router';
import queryString from "query-string";
const withPageRouter = (router) => {
router.query = { ...queryString.parse(router.asPath.split(/\?/)[1]) };
return router;
};
function getRouterParams(){
const router = useRouter();
router = withPageRouter(router);
return router;
}
export async function getTown() {
const town = await getRouterParams();
return town;
}
NOw when I attempt to run it, I get this error:
Server Error
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
This error happened while generating the page. Any console logs will be displayed in the terminal window.
Source
lib/api.js (34:26) # getRouterParams
32 |
33 | function getRouterParams(){
> 34 | const router = useRouter();
| ^
35 | router = withPageRouter(router);
36 | return router;
37 | }
But to me it looks like it should be fine; it is in a function body? I feel like i'm missing something obvious. I appreciate the help.
You can't be call useRouter() in normal function.
You can call only useRouter() inside of Top of the React function component or custom hooks
Learn more about Rules of Hooks here : https://reactjs.org/docs/hooks-rules.html
As an alternative to useRouter you might want to use withRouter (can be used for class components). Also see following related SO question:
How to use "useRouter()" from next.js in a class component?
import { withRouter } from 'next/router'
import React from "react";
export default withRouter(class extends React.Component {
render() {
return (
<div>{ this.props.router.query.id }</div>
)
}
})
Related
Suppose my URL looks something like this:
/blog/[post_id]/something
What is the recommended way to pass $post_id down to any component anywhere in the tree?
I know how to retrieve route parameters using getInitialProps but passing the values down is always giving me a hard time.
For pages I could technically use React Contexts although this seems a bit oversized for such a trivial use case.
For layouts I am honestly completely lost because pages are children of layouts and the return value of getInitialProps is passed to the page and not the layout.
My components could make use of useRouter but this requires useEffect and would also make my component depend on the route itself...
Any advice would be welcome (:
My components could make use of useRouter but this requires useEffect and would also make my component depend on the route itself...
useRouter seems like the obvious solution here. I'm not exactly understanding your concerns regarding the component depending on the route. I guess it does make the Layout less flexible since it needs to know that the post id is stored in the post_id query variable. But I would do it anyways :) It gives you a nice and simple way to access the query variables which can be used in a Layout that's outside of your BlogPost or in a deeply-nested component that you use inside the BlogPost.
Using the per-page layouts approach:
/components/Layout
import { useRouter } from "next/router";
import { ReactNode } from "react";
export default function Layout({ children }: { children: ReactNode }) {
const router = useRouter();
return (
<div>
<h3>You are viewing post id #{router.query.post_id}</h3>
{children}
</div>
);
}
/pages/blog/[post_id].jsx
import Layout from '../../components/Layout';
export default function BlogPost() {
return <div>Hello World</div>
}
BlogPost.getLayout = function getLayout(page) {
return (
<Layout>
{page}
</Layout>
)
}
/pages/_app.tsx (to support per-page layouts, copied from docs)
export default function MyApp({ Component, pageProps }) {
// Use the layout defined at the page level, if available
const getLayout = Component.getLayout || ((page) => page)
return getLayout(<Component {...pageProps} />)
}
I think the easiest and the cleanest way is to use window.location.pathname. this will give you the part after the domain name. for example for
http://localhost:3001/blog/[post_id]/something
you will get /blog/[post_id]/something
const pathname=window.location.pathname
const splittedPathname=pathname.split("/") // ['', 'blog', '[post_id]', 'something']
const dynamicId=splittedPathname[2]
you can run above code in useEffect and set a state. or you could write a hook and use it in the components that under dynamicId components
import React, { useState, useEffect } from "react";
const usePathname = () => {
const [postId, setPostId] = useState("");
useEffect(() => {
const pathname = window.location.pathname;
const splittedPathname = pathname.split("/");
const dynamicId = splittedPathname[2];
setPostId(dynamicId);
}, []);
return { postId };
};
export default usePathname;
If you are looking for client side rendering, useRouter is the best way to go. If you are looking for SSR or SSG, you should rather use getStaticProps or getServerSideProps.
I have a React app created with create-react-app.
I'm trying to make a custom hook using Microsoft Authentication Library (MSAL). MSAL has a custom React hook that I want to call from my own custom hook.
When I use a hook (any hook) inside my custom hook in a separate file I get this in the browser:
Warning: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
1. You might have mismatching versions of React and the renderer (such as React DOM)
2. You might be breaking the Rules of Hooks
3. You might have more than one copy of React in the same app
// ourhook/index.ts
import { useEffect } from "react";
export const useMsal2 = () => {
useEffect(() => {
console.log("Hello from our hook!");
});
};
// app.tsx
import React from "react";
import { useMsal2 } from "./ourhook";
const App = () => {
useMsal2();
return <div>App</div>;
};
export default App;
If I call
const { instance } = useMsal();
directly from App.tsx everything works fine. It only appears to be a problem if my custom hook is in its own file.
From what I see I'm not violating any hook rules. I'm calling a hook that's calling a hook, and the first call is from a top level component.
I have read other threads here about hooks in hooks, but none of them has an answer that fits this problem.
Have I missed something about hook rules, or what might be causing this?
Okay, I forgot that we tried to have /ourhook as a freestanding project and then copy pasted it into a create react app app.
Some of you were right, it did have its own version of react.
I'm just going to hide under a rock for the rest of the week.
Thanks for all your help! <3
Try to add this comment just above:
import { useMsal } from "#azure/msal-react";
export const useMsal2 = () => {
// eslint-disable-next-line react-hooks/rules-of-hooks
const { instance } = useMsal();
const request = "";
return {
loginRedirect: () => console.log(""),
}
};
I don't know what useMsal looks like, but from what I see, you don't actually violate any hook rule.
I have a NextJS app. I want to add a function that can redirect to any page using nextjs routing.
For example, after finishing signup I want to redirect to a certain page.
If I create this function (reusable everywhere) :
import { useRouter } from 'next/router'
const goTo = (href) => {
const router = useRouter()
router.push(href)
}
I want to add this to my signup Logic, the problem is that I break React Hooks rules :
react-dom.development.js?ac89:14906 Uncaught (in promise) Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
You might have mismatching versions of React and the renderer (such as React DOM)
You might be breaking the Rules of Hooks
You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
And effectively useRouter is a React Hook, and I'm trying to call it outside a React function, as stipulated here https://reactjs.org/docs/hooks-rules.html it will not work.
How can I then have a routing solution for NextJS to be callable in regular Javascript ?
So If you're using purely React.js (without Next.js on top of it), you can simple do it this way:
Import React from 'react'
export const handleRoutes = (url) => {
const history = React.useHistory()
return history.push(url)
}
Then You'd import this regular js function in any of your react files, like this:
import { handleRoutes } from 'fileName.js'
<button onClick={() => handleRoutes("/routeToBeRedirectedTo")}> Click to redirect </button>
However when using Nextjs I'm not sure that the above way would work. My personal method would be simply implementing this function (in a utility.js file):
export const handleRedirect = (router, url) => {
return router.push(url)}
Then just importing the function & useRouter hook in the file you want:
import { handleRedirect } from "./utility.js"
import { useRouter } from "next/router"
const router = useRouter
Then inside your JSX return statement:
<button onClick={() => handleRedirect(router, "/routeToBeRedirectedTo")}> Click to redirect </button>
And if it's a redirect after sign in/sign up, just simply useEffect like so:
// depends if you're storing your user credentials in your local storage or cookies, this example below would be if your User credentials are stored in localstorage
const user = JSON.parse(localstorage.getItem("user"))
UseEffect(() => {
if (user) return handleRedirect(router, "/routeToBeRedirectedTo")
}, [user])
My App was working fine and suddenly i got this error.
Error: Invalid hook call. Hooks can only be called inside of the body of a function component. This could happen for one of the following reasons:
You might have mismatching versions of React and the renderer (such as React DOM)
You might be breaking the Rules of Hooks
You might have more than one copy of React in the same app
See https://reactjs.org/link/invalid-hook-call for tips about how to debug and fix this problem.
import { useContext } from "react";
import jwtDecode from "jwt-decode";
import AuthContext from "./context";
import authStorage from "./storage";
const useAuth = () => {
const { user, setUser } = useContext(AuthContext);
const logIn = (authToken) => {
const user = jwtDecode(authToken);
setUser(user);
authStorage.storeToken(authToken);
};
const logOut = () => {
setUser(null);
authStorage.removeToken();
};
return { user, logIn, logOut };
};
export default useAuth;
All looks fine. except maybe actually importing React
import React, { useContext } from "react";
I know you don't need this for React from React 17, but there's no official statement from react native saying they use the new JSX compiler that doesn't require the import statement
also check the AuthContext file you imported
I started a project with next js and typescript. I have a main component that I call it in the index.js page I use the getStaticProps function in the main component getStaticProps returns a prop object and when I log this prop in my main component I received undefined in my console.
I want to know using the getStaticProps in the component is wrong and I have just to use that function in pages or not.
I am a newbie in next js and I would be very grateful if anyone could help me.
this is my main component
import React from 'react';
import {IMain} from "../../../../interfaces/components/IMenu/IMain";
const Main:React.FC<IMain> = (props) => {
console.log(props);
return (
<div>
</div>
);
};
export async function getServerSideProps() {
return {
props: {
data: 'ggwp'
}
};
}
export default Main;
and this is my index.js page
import Text from "./../components/ui/Text/Text";
import Button from "../components/ui/Button/Button";
import Main from "../components/Menu/Desktop/Main/Main";
const Home = () => {
return <Main/>;
};
export default Home;
getStaticProps can only be exported from a page. You can’t export it from non-page files.It will not work if you add getStaticProps as a property of the page component.
https://nextjs.org/docs/basic-features/data-fetching
Here's a possible solution:
Using a node script (like predev) to fetch your content and store it in JSON files in your project, then reference those JSON files in your component.
Posted about it here:
https://dev.to/brewhousedigital/nextjs-getstaticprops-with-components-f25
Solution
used react's useEffect() for component
and for page getStaticProps() of next.js
after combine the two will have hybrid page