1

I found this question, which describes exactly what I was looking for...

Pass object through Link in react router

Is it possible to pass an object via Link component in react-router?

Something like:

<Link to='home' params={{myObj: obj}}> Click </Link>

In the same way as I would pass props from the Parent to Child component.

If it's not possible what is the best way of achieving this: I have a React + Flux app, and I render the table with some data. What I am trying to do is when I click on one of the rows it would take me to some details component for this row. The row has all of the data I need so I thought it would be great if I could just pass it through Link.

The other option would be to pass the id of the row in the url, read it in the details component and request the data from the store for by ID.

Not sure what is the best way of achieving the above...

I agree with the author's conclusion, meaning: instead of passing an object, we should pass an id. I am however struggling with where on the next component I should perform that lookup, possibly in an onload method where I define mapDispatchToProps.

However, I don't know how to access the state from there to see if the object is in the state so I can retrieve it from an api call if it isn't in the state. Does that belong here or in the action? If it is in the action, how do I get it there. This seems like it would be a very basic pattern and I am missing something.

Community
  • 1
  • 1
Mr. Awesome
  • 47
  • 1
  • 6

1 Answers1

0

You use it with redux-thunk and you can make action for the router.

I mean something like this

export const boundAllStreams = (nextState, replaceState) => reqStreams(nextState.params.game);

So you can see I use the params game and change the state with

export const reqStreams = game => {

  const promise = new Promise((resolve, reject) => {
    request
      .get(`${config.ROOT_URL}/${game}&client_id=${config.API_KEY}`)
      .end((err, res) => {
        if (err) {
          reject(err);
        } else {
          resolve(res.body.streams);
        }
      });
  });

  return {
    type:    types.RECEIVE_STREAMS,
    payload: promise
  };

};

Here this is my reducer where I got my params from the router action.


After you need to do something like this, you bind your action and make it a object.

const boundRouteActions = bindActionCreators(routeActions, store.dispatch);

And finally in the router you can dispatch the action with the onEnter api from react-router

      <Route path=":game">
        <IndexRoute
          component={StreamsApp}
          onEnter={boundRouteActions.boundAllStreams} />
    </Route>

Hope that can help you ;). I know I just show you code but I'm sure that can help yo figured out how to implement this ;)

EQuimper
  • 5,811
  • 8
  • 29
  • 42