From f7c886a6e1e9f82873747e8fa7ae732ba57665e4 Mon Sep 17 00:00:00 2001 From: Noah Loomans Date: Fri, 2 Feb 2018 16:11:27 +0100 Subject: Don't send fetch request during render --- src/client/react/components/container/View.js | 67 +++++++++++++++++++-------- 1 file changed, 47 insertions(+), 20 deletions(-) diff --git a/src/client/react/components/container/View.js b/src/client/react/components/container/View.js index bd75c9c..f919dbc 100644 --- a/src/client/react/components/container/View.js +++ b/src/client/react/components/container/View.js @@ -10,28 +10,55 @@ import extractSchedule from '../../lib/extractSchedule'; import Schedule from '../presentational/Schedule'; import Loading from '../presentational/Loading'; -const View = ({ - schedules, - match, - location, - dispatch, -}) => { - const user = userFromMatch(match); - const week = weekFromLocation(location); - const schedule = extractSchedule(schedules, user, week); - - switch (schedule.state) { - case 'NOT_REQUESTED': +class View extends React.Component { + componentDidMount() { + this.fetchScheduleIfNeeded(); + } + + componentDidUpdate() { + this.fetchScheduleIfNeeded(); + } + + fetchScheduleIfNeeded() { + const { + schedules, + match, + location, + dispatch, + } = this.props; + + const user = userFromMatch(match); + const week = weekFromLocation(location); + const schedule = extractSchedule(schedules, user, week); + + if (schedule.state === 'NOT_REQUESTED') { dispatch(fetchSchedule(user, week)); - return ; - case 'FETCHING': - return ; - case 'FINISHED': - return ; - default: - throw new Error(`${schedule.state} is not a valid schedule state.`); + } } -}; + + render() { + const { + schedules, + match, + location, + } = this.props; + + const user = userFromMatch(match); + const week = weekFromLocation(location); + const schedule = extractSchedule(schedules, user, week); + + switch (schedule.state) { + case 'NOT_REQUESTED': + return ; + case 'FETCHING': + return ; + case 'FINISHED': + return ; + default: + throw new Error(`${schedule.state} is not a valid schedule state.`); + } + } +} View.propTypes = { schedules: PropTypes.objectOf(PropTypes.objectOf(PropTypes.shape({ -- cgit v1.1