Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

React-Router throws Invariant Violation on setState() in ajax call

I'm trying to find a tricky error that I'm experiencing with react-router. For some reason, setting the state of one of my child components in a top-level page route causes the following error:

Uncaught Error: Invariant Violation: Missing "userId" parameter for path "/user/:userId" 

This error happens regardless of whether or not I am navigating to that path. My routes look this:

var routes = (
  <Routes>
    <DefaultRoute handler={LoginPage} />
    <Route name="login" handler={LoginPage} />
    <Route name="home" handler={HomePage} />
    <Route name="category" path="/category/:category" handler={CategoriesPage}/>
    <Route name="profile" path="/user/:userId" handler={ProfilePage}/>
  </Routes>
);

And my ajax call looks like this:

var Feed = React.createClass({
  getInitialState: function() {
    return { feedItems: [] };
  },

  componentDidMount: function() {
    $.ajax({
    url: '/api/transactions',
    dataType: 'json',
    success: function(transactions) {
      this.setState({ feedItems: transactions });
    }.bind(this),
    error: function(xhr, status, err) {
      console.error(this.props.url, status, err.toString());
    }.bind(this)
  });
},

....

This Feed is generated on a bunch of pages, including the HomePage and the ProfilePage. I'm having a lot of trouble figuring out how the :userId parameter could be related to the Ajax call in the feed, but that's where the stack trace leads me. Any help with what is going on here would be much appreciated.

UPDATE: Found the problem. My mongo database was out of date (model schemas changed), which was causing a host of problems, bubbling up to this Invariant Violation. I'm still not entirely sure how the two were related, but deleting old objects fixed the problem.

like image 886
ritmatter Avatar asked Dec 12 '22 03:12

ritmatter


2 Answers

Thanks, @ritmatter for solving this yourself ! Just as a reference, here the answer with a link to the docs.

Remember in all your react-router <Link> elements you have in your code, to include the params object for links pointing to a parameterized route:

<Link to="BillingInfo" params={userId:"user876718236"}>Your Billing Information</Link>
<!-- linking to /user876718236/billing-info -->

Have a look here for details: react-router/Link

UPDATE [2015-03-29] corrected JSX param braces. Thanks to @Akay.

like image 132
AlexGrafe Avatar answered Dec 20 '22 03:12

AlexGrafe


UPDATE: v1.0 (November 2015)

Named paths are no longer supported, you link to full paths. String templates in ES6 are handy for this:

// v0.13.x
<Link to="user" params={{userId: user.id}}>Mateusz</Link>

// v1.0
<Link to={`/users/${user.id}`}>Mateusz</Link>

From Changelog: Links.

like image 42
Jan Klimo Avatar answered Dec 20 '22 03:12

Jan Klimo