Unable to use router.push in Reactjs - javascript

I am working on Reactjs and using nextjs,Right now i am trying to refresh page (using routes) but i am getting following error
Error: No router instance found. you should only use "next/router" inside the client side of your app.
Here is my current code
const Post = ({ post, blogs }) => {
const routers = useRouter();
var spath=routers.asPath;
routers.push({ pathname: spath, query: '' });
})

You probably used router outside of a functional component or hook.
Convert Post to hook and it should work.

If you are running this code on application load or on any data change. You should do this inside useEffect hook because while rendering application on sever router won't be there and useEffect runs only inside browser.

Related

Next.js equivalent for useRouteMatch

I'm migrating a React app to Next.js.
Since Next.js doesn't use "react-router-dom", I need to change some of the React Router hooks so that they work with Next.js.
One of them is useRouteMatch.
I want to get this line of code to work with Next.js -
const match = useRouteMatch<{lang?: Language}>('/map/:lang([a-z]{2})?');
I haven't managed to find an equivalent method or workaround for this yet.
Does anyone have any suggestions?
Everything about nextjs route is in next/route.
You might be looking at router.pathname
const Component = () => {
const router = useRouter() //now u can use the router object
}
https://nextjs.org/docs/api-reference/next/router#router-object

How do I add id parameters to the url of a html page?

I would like to access URL parameters from a website I'm creating using ReactJS and webpack. I have multiple webpages and one webpage is a universal blog post view page. Instead of having to make multiple pages for each blog post, I want to be able to load the blog post by the blog id. When I do this, however, the page expects another page with the blog_id. For example, if the blog id is "test_blog", the URL would be: https://www.example.com/anotherpage/test_blog.
I know that ReactJS has a Link component that handles navigating to different react pages, but it only seems to work in a single page react application. I'm working on a multiple page react application because of the meta data I want to have on each page that I generate.
Would I have to add JavaScript code to the html page itself to get around it, or is there a ReactJS solution?
If I understand correctly, you could do it the same as I did
export const fetchData = async (newFetchOffset) => {
// console.log(fetchOffset);
const res = await axios(`https://xoosha.com/ws/1/test.php?offset=${newFetchOffset}`)
return res.data
}
the Repository is available at THIS IS A LINK
Add route definition for sub page
<Route path="/subpage/:id">
<SubPageComponent />
</Route>
Now in sub page component:
import { useParams } from 'react-router';
export default function SubPageComponent() {
const { id } = useParams();
}
Also, why do you have .html in route, please read the docs of react and any routing library: https://v5.reactrouter.com/web/example/url-params
For non react router way:
window.location.href.split('/').reverse()[0]

Use nextjs routing outside react hooks in regular javascript

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])

Nuxt Dynamic Routing on Firebase

My Nuxt.js App has this structure:
/pages/index.vue
/pages/_slug/index.vue
When user gets /{any_page}, it will use the path to build the page content:
/pages/_slug/index.vue
<template>
<div>
{{slug}}
</div>
</template>
<script>
import fetch from 'isomorphic-fetch';
export default {
async asyncData({ params }) {
return { slug: params.slug }
}
}
</script>
This works perfectly when running the Nuxt App directly via yarn dev.
When I try to run this using firebase functions:
$ firebase serve --only functions,hosting
The static routes work perfectly, but the dynamic routes always render the default / page, instead of executing the dynamic one. How do I fix this?
If using nuxt generate, then the explanation below should work. If using nuxt build, look at this repo, it is a template i wrote for nuxt + firebase as ssr.
Generate says it skips over dynamic routes, unless you explicitly specify them, hence 404 errors. In your Nuxt config file, you want to specify those routes. Here is an example of fetching from the database during generation. Note that in my example below, the doc id is the slug for the page.
nuxt.config.js
generate: {
async routes() {
const { db } = require('./services/fireInit');
const qs = await db.collection('recipes').get();
return qs.docs.map(x => `/recipes/${x.id}`);
}
},
The downside to this approach is as you add new items via a CMS, you will need to rebuild/deploy your site each time if you want to be able to use these new links without a 404. CMS without redeploy does work if you navigate to new content 'organically'...404 only occurs on a page refresh or on jumping directly to the page from a hyperlink.

How to add dynamic component to Angular Router

I'm creating pluggable angular app.
I've found the following article:
Building an extensible Dynamic Pluggable Enterprise Application with Angular
Generally, everything works fine, but when I've tried to add angular router then I met some problems.
Currently, I'm not able to add the dynamically loaded component to the router.
I've tried something like this:
this.pluginLoader.load(pluginName).then(moduleFactory => {
const moduleRef = moduleFactory.create(this.injector);
const entryComponent = (moduleFactory.moduleType as any).entry;
const compFactory = moduleRef.componentFactoryResolver.resolveComponentFactory(
entryComponent
);
this.router.config.push({
path: `${pluginName}`,
component: entryComponent
});
this.router.resetConfig(this.router.config);
this.router.navigate([`/${pluginName}`]);
});
But this code cause following error:
core.js:15723 ERROR Error: Uncaught (in promise): Error: No component factory found for function(){this.x=!1}. Did you add it to #NgModule.entryComponents
I've tried also use loadChildren property instead of the component property but I don't know what path should I use.
How can I add the component to the component factory, or how can I find a proper path for such components?
I've found a solution, to add the dynamically loaded module to the angular router we have to use LoadChildren property, but directly from Route object. In this case, we have to create Route object first and then add it to the router config.
loadPlugin(pluginName: string) {
this.pluginLoader.load(pluginName).then(moduleFactory => {
const route: Route = {
path: `${pluginName}`,
loadChildren: () => moduleFactory
};
this.router.config.push(route);
});
}

Categories

Resources