Giter Club home page Giter Club logo

connected-next-router's People

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

connected-next-router's Issues

Doesn't support NextJS 9.0.5

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?

Add query into location

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,
  };
};

next-routes support

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!

Question

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

Integration in Saga

Hello,

Is it possible to use this library in Redux Saga, if so how?

Thanks in advance.

ModuleNotFoundError: Module not found:

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

State updates after the first useEffect(() => {}, []) called.

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.

Using in reducer

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 push method from next/router not working properly as expected after wrapping my app with ConnectedRouter

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

Example without `next-redux-wrapper`

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.

Context `store` not defined with basic setup

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?

Requests with query parameters are being redirected to /

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

Redirects to / on refresh

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 you always add the above component to your tree - and then go to an arbitrary non-root page and refresh the browser - then connected-next-router will navigate the browser to / and then back to e.g. /blog. :( NOT always, however; only once in a while. Here's a screenshot of the bug in action;

image

This causes redirect flows with oauth2 to fail.

Redux Persist

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.

Expose a LocationChangeAction type for TypeScript?

Similar to #86. I'd be happy to send a PR for both/either of these issues.

TypeScript playground example

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

Why not just use Router.push?

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?

๐Ÿ˜‚

search.replace is not a function

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)

Doesn't consider basePath?

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!

TypeScript signatures

It would help consuming this library if there were typescript signatures available as part of the package.

Feature request: createMatchSelector to replace connected-react-router

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.

Export a NextRouterState type for TypeScript?

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

export type RouterState = {
is what I'm looking for? But it's not exported right now.

Redux Toolkit

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..

Using the browser back button throws a TypeError

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.

doesn't work with React 18+

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.

add PREFETCH

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

[Question] How to get URL parts in a Reducer?

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)

push method reloads page

I'm using push method to change url query params. There are two issues I see:

  1. I want to update only query params, so I only pass query without pathname. But application crashes.
  2. When I pass query and pathname(the current page url) it works, but page is fully reloaded from the server with new url params. How to avoid page reloading? I just changed query params, why is it reloading?

react-router migration question

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?

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.