danielr18 / connected-next-router Goto Github PK
View Code? Open in Web Editor NEWA Redux binding for Next.js Router compatible with Next.js.
License: MIT License
A Redux binding for Next.js Router compatible with Next.js.
License: MIT License
Hey! I'm trying to apply your library for Next 9.0.5 and i get the error:
[ error ] ./node_modules/connected-next-router/es/patchRouter.js
Module not found: Can't resolve 'next/dist/next-server/lib/router/rewrite-url-for-export' in '{projectPath}/node_modules/connected-next-router/es'
That's because you're importing rewriteUrlForNextExport
over there, but NextJS 9.0.5 doesn't exports it.
Updating to [email protected] solves the problem.
Maybe you'll add some info about that or more readable error?
Hello.
Can you update your locationFromUrl function. It would be very good to have an object with query parameters in redux store.
For example:
var locationFromUrl = function locationFromUrl(_url) {
var url = _typeof(_url) === 'object' ? (0, _url2.format)(_url) : _url;
var _parse = (0, _url2.parse)(url),
hash = _parse.hash,
search = _parse.search,
pathname = _parse.pathname;
var query = {};
var str = typeof search === 'string' ? search.substring(1) : '';
str.replace(/([^=&]+)=([^&]*)/g, function(m, key, value) {
query[decodeURIComponent(key)] = decodeURIComponent(value);
});
return {
pathname: pathname,
search: search ? search : '',
hash: hash ? hash : '',
query: query,
};
};
Would be great to have an option to change the hardcoded type action name such as this one
https://github.com/danielr18/connected-next-router/blob/master/src/actions.ts#L11 .
Readme.md says about next-routes support, but it doesn't work out of the box and there's no docs about it.
After digging into connected-next-router
sources I found that you need to
import {Router} from './routes';
const routerMiddleware = createRouterMiddleware({
Router,
methods: {
push: 'pushRoute',
replace: 'replaceRoute',
prefetch: 'prefetchRoute',
},
}),
to get it work properly with next-routes
router. I'm not sure it can handle all kinds of arguments that these methods should handle, but at least it works with url strings.
I think this worth mentioning in the docs. Thanks!
Hello @danielr18 ,
Some example of how to use this that does not work for me from your PUSH
push(href, as, { shallow: false })
Thank you.
Regards.
P.D: Thank you for implement the prefeching
Hello,
Is it possible to use this library in Redux Saga, if so how?
Thanks in advance.
Uncaught (in promise) TypeError: (0 , n._rewriteUrlForNextExport) is not a function
next@^8.0.3
When I try to build the nextjs project I get this error:
info - Creating
build
Failed to compile
ModuleNotFoundErr
ror: Package path
ed from package C
omebox\homebox-ne
d-next-router (se
ers\chas13\Deskto
ode_modules\conne
.json)
Build error occ
Error: > Build fa
errors
at C:\Users\c
mebox-next\node_m
ndex.js:397:19
at async Span
chas13\Desktop\ho
modules\next\dist
s:60:20)
at async Obje
:\Users\chas13\De
xt\node_modules\n
77:25)
C:\Users\chas13\D
ext> Module not f
h ./actions is no
C:\Users\ch
It's very troublesome because you can't normally use values from store.router.location to call some clientSide requests immediately because the value there hasn't updated yet after navigation.
I was able to manage with it using useRouter, but then here's a question why should I use the lib, if I can't even do something like this.
To fix it we can update the store on the routeChangeStart
event, I don't see many downsides in it.
Hello Daniel !
Is it possible to use your module from reducer switch ? For example :
const apiMiddleware = store => next => action => {
next(action);
switch (action.type) {
case LOGIN_THROUGH_API:
console.log('callApi ...');
// Push to new route
break;
}
};
Thank you ๐ช
my app.js
push not working properly
router.push({
pathname: home/${productName}/${id}/view
,
query: { previousLabel }
})
Error from project
Unhandled Runtime Error
TypeError: url.startsWith is not a function
Source
next-server\lib\router\router.ts (97:6) @ isLocalURL
95 | */
96 | export function isLocalURL(url: string): boolean {
97 | if (url.startsWith('/')) return true
| ^
98 | try {
99 | // absolute urls can be local if they are on the same origin
100 | const locationOrigin = getLocationOrigin()
I am using Next.js to create a SPA and wont be leveraging any Next.js lifecycle methods, meaning I don't have to maintain server/client store parity. I would just do it anyways, but next-redux-wrapper
opts the application out of automatic static exports.
I also commented here so that I can help to circle back and update documentation on this matter on the other end.
Hi, I'm hitting a fairly strange issue. I've tried looking through the source to figure out why this is happening, but I'm hitting this error:
Warning: Failed context type: The context `store` is marked as required in `WithConnectedRouter`, but its value is `undefined`. in WithConnectedRouter (created by Application) in Provider (created by Application) in Container (created by Application) in Application (created by withRedux(Application)) in withRedux(Application)
In pages/_app.js
:
<Provider store={store}>
<ConnectedRouter>
<Component {...pageProps} />
</ConnectedRouter>
</Provider>
My store
is defined as:
export default function configureStore(initialState = {}, options) {
const persistedReducer = persistReducer(
{
storage: localForage,
key: 'primary',
whitelist: ['client'],
},
rootReducer
);
const reducer = isServer ? rootReducer : persistedReducer;
if (options.isServer) {
initialState.router = initialRouterState(options.asPath);
}
const routerMiddleware = createRouterMiddleware();
return createStore(reducer, initialState, composeWithDevTools(applyMiddleware(thunkMiddleware, routerMiddleware)));
}
It should be mentioned that the rest of things (redux, connect on page components, etc) all work fine, and it appears that my routerMiddleware
is also working. Any ideas why this might be happening or anything I'm doing wrong?
There is a bit of code in ConnectedRouter.js that checks for "locationMismatch" on store changes. This mismatch apparently also happens when a request contains query parameters.
Maybe it doesn't happen in every use case of connected-next-router, so I'll describe my setup:
I have one Next.js page that catches all routes ([[...slug]].js)
It uses getStaticPaths for a list of default paths to make static pages, and has fallback: true to ensure catching all routes.
ConnectedRouter is wrapper around the Component in _app.js
If you apply connected-next-router - client-side only โ
import React, { Component, ReactNode } from 'react'
import { Provider } from 'react-redux'
import { Store, applyMiddleware } from 'redux'
import { createRouterMiddleware, initialRouterState, ConnectedRouter } from 'connected-next-router'
import { createStore } from 'redux';
import { MakeStoreOptions } from 'next-redux-wrapper';
import { error } from '../lib/logary';
import { Router } from '../server/lib/routes';
// eslint-disable-next-line @typescript-eslint/no-unused-vars
function createStub(_: Record<string, any>, __?: MakeStoreOptions) {
const routerMiddleware = createRouterMiddleware({
Router,
methods: { push: 'pushRoute', replace: 'replaceRoute', prefetch: 'prefetchRoute' },
})
const enhancer = applyMiddleware(routerMiddleware)
return createStore((s: any) => s, { router: initialRouterState() }, enhancer)
}
export default class ReduxApp extends Component<{ children: ReactNode }, { store: Store }> {
constructor(props: any) {
super(props)
this.state = { store: createStub({}) }
if (typeof window !== 'undefined') {
import('./redux').then(
x => this.setState({ store: x.create({}) }),
err => error('Loading Redux failed', { error: err }))
}
}
render() {
return (
<Provider store={this.state.store}>
<ConnectedRouter>
{this.props.children}
</ConnectedRouter>
</Provider>
)
}
}
// export default withRedux(storeCallback)(ReduxApp)
/
and then back to e.g. /blog
. :( NOT always, however; only once in a while. Here's a screenshot of the bug in action;This causes redirect flows with oauth2 to fail.
Hi! Is this package compatible with react-redux@7 and next@9? Thank you :)
I'm interested in an example that works with redux-persist. I have trouble getting this to work with it, but I think it's fairly common for one to want to persist the state with redux-persist
.
Similar to #86. I'd be happy to send a PR for both/either of these issues.
example.ts:1:27 - error TS2305: Module '"connected-next-router"' has no exported member 'LocationChangeAction'.
1 import { LOCATION_CHANGE, LocationChangeAction } from "connected-next-router";
The type is exported from connected-react-router
: https://github.com/supasate/connected-react-router/blob/c6609e335c1b6bd3a2fce163d4d19beeb6d6a7ea/index.d.ts#L41
This might be a silly question, but I installed this package from npm without realizing that I can just use import Router from 'next/router'
and Router.push('/home')
to switch routes from inside an action. So, what is the point of this package?
๐
Replace method is not working .
Expected is for this to work as it does in connected-react-router
const state = store.getState()
store.dispatch(
replace({
pathname: state.router.location.pathname,
search: {
...state.router.location.search,
...action.pushToUrl
}
})
)
but it throws an error
Uncaught TypeError: search.replace is not a function
at formatUrl (format-url.js?e83e:22)
at formatWithValidation (utils.js?83fd:5)
at resolveHref (router.js?7a5c:24)
at prepareUrlAs (router.js?7a5c:29)
Does this not take basePath into consideration?
I have "/frontend" as my basePath
and I'm seeing this in the logs (using redux-logger):
CHANGED: router.location.href /frontend/auth/login โ /auth/login
CHANGED: router.location.pathname /frontend/auth/login โ /auth/login
Not sure what the expected behaviour should be, but:
Should this route change even register, since they're basically the same paths?
Should "/frontend" either be added to, or omitted from both before-and after-states?
Great module BTW!
It would help consuming this library if there were typescript signatures available as part of the package.
Similar issue to #89. We are using [email protected]
. It works with npm install --force
but it would be good to not have to do that.
npm ERR! Could not resolve dependency:
npm ERR! peer react-redux@"^7.1.0" from [email protected]
npm ERR! node_modules/connected-next-router
npm ERR! connected-next-router@"^4.2.0" from the root project
I am migrating from client side rendering to next.js
for SSR. Although connected-next-router
is supposed to replace connected-react-router
(with the basic analogical name) it does not include a very basic functionality to match to opponent. I haven't covered everything thats missing but found that this can be included in the library itself very easily to fast line the migration process.
Hi, I just found this library while converting an app written in TypeScript from CRA+react-router to Next.js. Thank you so much for saving me from having to refactor a bunch! ๐
One small point: there's no good exported type I can find for the router
part of state. Back in connected-react-router
land we had RouterState
. Could this library please export an equivalent?
It looks like
connected-next-router/src/types.ts
Line 10 in c2b0787
Hi there, this is less of an issue and more of a request.
Could you maybe make an example of how to use this with redux.toolkit and slices?
I tryed getting it working but am rather new to redux.
Thanks a lot..
Hello,
My question is if we can know in any way which was the route from which it came or the stack or stack of routes.
Regards
When using the browser back button, routing still works, but it throws an error:
Uncaught TypeError: Cannot read property 'apply' of undefined
at Router._bps (patchRouter.js:72)
at Router.onPopState (router.js:36)
It relates to the line where _unpatchedBeforePopStateCallback
is called in patchRouter.js
, which is not defined.
I did some research and found out that _beforePopState
is not there anymore in Next.js:
vercel/next.js@83334f1#diff-a33404ba5698b3b45e69c2b3f2d3b48bL38
Then I tried replacing _beforePopState
with _bps
in patchRouter.js
, but that did not help.
Maybe someone has an idea.
npm ERR! code ERESOLVE
npm ERR! ERESOLVE unable to resolve dependency tree
npm ERR!
npm ERR! While resolving: undefined@undefined
npm ERR! Found: [email protected]
npm ERR! node_modules/react
npm ERR! react@"18.0.0" from the root project
npm ERR! peer react@"^17.0.2 || ^18.0.0-0" from [email protected]
npm ERR! node_modules/next
npm ERR! next@"12.1.4" from the root project
npm ERR! peer next@"^10.0.0 || ^11.0.0 || ^12.0.0" from [email protected]
npm ERR! node_modules/connected-next-router
npm ERR! connected-next-router@"*" from the root project
npm ERR! 1 more (react-dom)
npm ERR!
npm ERR! Could not resolve dependency:
npm ERR! peer react@"^16.8.0 || ^17.0.0" from [email protected]
npm ERR! node_modules/connected-next-router
npm ERR! connected-next-router@"*" from the root project
npm ERR!
npm ERR! Fix the upstream dependency conflict, or retry
npm ERR! this command with --force, or --legacy-peer-deps
npm ERR! to accept an incorrect (and potentially broken) dependency resolution.
I have fork with Immutable.js support, you can use it.
Connected to routing, but probably not in this library, because it may be a nextjs difference of package versions/mixup that causes this. developit/preact-redux#43 Feel free to close.
Hello,
Thank you for your contribution to the community @danielr18 .
i have seen that the router.prefetch method missing and it could be fine to put it
Thank you.
Regards
Does this work with React 18, Next 13 maybe with the app directory?
Hi @danielr18 thanks for making this.
I have a problem where i'm in a reducer, and the current path could be like /static1/static2/dynamic1/dynamic2
, or it could be /dynamic1/dynamic2
, and I need to extract & use dynamic1
and dynamic2
. I want to find a solution that is agnostic to the values of staticN.
I would have used useRouter()
and examined the query
, but i'm in a reducer so I can't.
I was hoping that using connected-next-router
to put the router's state into redux would let me do this, but I cannot see how. Any ideas? (I've gotten to the point where I can see the router's state in redux)
I'm using push method to change url query params. There are two issues I see:
I've got the following middleware in place: thunk.withExtraArgument({ history }),
How do I pass the relevant object into here when using connected-next-router
?
Doesn't seem to work with https://github.com/omnidan/redux-undo
If I go from /
to /example
I can see the event triggered on the redux console and the store is changed, but if I open a new tab with /example
directly, the store shows /
as pathname
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.