Here's a class component I'd like to refactor to a functional component using useReducer
export default class FootballMatchesData extends Component {
constructor(props) {
super(props);
this.state = {
selectedYear: null,
matchData: [],
firstCall: false
};
}
chooseYear = (year) => (e) => {
this.setState({
selectedYear: year
})
axios.get(`https://website?property=${year}`)
.then(res => {
this.setState({ matchData: res.data, firstCall: true })
})
}
render() {
...
}
}
I'm stuck at defining the 'CHOOSE_YEAR' case of my reducer. How would I define that case so that it:
- updates
selectedYear
- makes an api call to
https://website?property=${year}
, then populatesmatchData
- updates
firstCall
Here is my current refactor. https://codesandbox.io/s/gracious-pare-um66h?file=/src/FootballMatches.js
You seem unfamiliar with the reducer pattern. Reducers are pure functions taking a state object and action to apply to that state, and returns the next state object. There are zero side-effects in reducer functions.
Use an
useEffect
hook to fetch the data whenyear
updates in state. You may not want to also use anchor tags for the year list options since clicking that will likely try to navigate or reload the app/page.