score:1

Accepted answer

you are close to the solution, you just need to compare the new userid prop with the old one to prevent the infinite loop:

import { connect } from "react-redux";
import { link } from "react-router-dom";
import { fetchruns } from "../actions";
import runcell from "./runcell";

class runs extends react.component {
  componentdidupdate(prevprops) {
    if(prevprops.userid !== this.props.userid){ // <=== in order to prevent infinite loop add this comparison
       this.props.fetchruns(this.props.userid);
    }
  }

  componentdidmount() {
    if(this.props.userid){ // <=== fetch your data inside this methode
      this.props.fetchruns(this.props.userid);
   }
  }

  renderruns() {
    //show runs in reverse chronological order
    const sortedruns = this.props.runs.sort(
      (a, b) => new date(b.rundate) - new date(a.rundate)
    );

    return sortedruns.map((run) => {
      return <runcell {...run} key={run.id} />;
    });
  }

  render() {
    if (this.props.runs) {
      return (
        <div classname="ui container">
          <div classname="ui secondary pointing menu">
            <h3>your training log</h3>
            <div classname="right menu">
              <link classname="ui button right" to="/runs/add">
                add run
              </link>
            </div>
          </div>
          <div classname="ui">{this.renderruns()}</div>
        </div>
      );
    } else {
      return <div>loading runs...</div>;
    }
  }
}

function mapstatetoprops(state) {
  return { runs: object.values(state.runs), userid: state.auth.userid };
}

function mapdispatchtoprops(dispatch) {
  return {
    fetchruns: (userid) => dispatch(fetchruns(userid))
  }
}

export default connect(mapstatetoprops, mapdispatchtoprops)(runs);

Related Query

More Query from same tag