Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

How to pass URL params to static fetchData component method? #3

Open
si-harps opened this issue Aug 14, 2017 · 1 comment
Open

How to pass URL params to static fetchData component method? #3

si-harps opened this issue Aug 14, 2017 · 1 comment

Comments

@si-harps
Copy link

I'm keen to understand best practices for passing url params from the express route handler to the component being rendered server side. Currently, it looks as though the only way the is achievable is by using custom express routes when required or a hacky url split inside the static component method.

eg.

GET http://www.myapp.com/posts/:id (req.params.id required to load post 10 from external endpoint)

import { getPost } from './actions/post'

...

static fetchData(store) {
    // param 10 required from request url
    return store.dispatch(getPost(:id))
}

Any thoughts on this?

@si-harps
Copy link
Author

For anyone experiencing the same issue see below for the fix...

In routes/index.js see the line...

const promises = branch.map(({route}) => {
...
})

Each route being mapped will also contain a 'match' property. This property contains the url params as defined in the router. So if the match route is http://www.myurl.com/posts/:id, match.params.id will be the value of :id. So in full...

const branch = matchRoutes(routes, req.url);
const promises = branch.map(({ route, match }) => {

    let fetchData = route.component.fetchData

    return fetchData instanceof Function 
        ? fetchData(store, match) 
        : Promise.resolve(null)
})

...the static fetchData method on the component might look like this...

static fetchData(store, props) {
    return store.dispatch(getPost(props.params.id));
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant