sinusGob sinusGob - 4 months ago 18
React JSX Question

How do i properly do a GET request in react-redux?

My goal is to basically do a basic GET request in react-redux. I know how to do it with POST but not with GET because there is no event that is triggering the action.

Heres' the code for action

export function getCourses() {
return (dispatch) => {

return fetch('/courses', {
method: 'get',
headers: { 'Content-Type': 'application/json' },
}).then((response) => {
if (response.ok) {
return response.json().then((json) => {
dispatch({
type: 'GET_COURSES',
courses: json.courses
});
})
}
});
}
}


Where do i trigger this to get the data? in component?

import React from 'react';
import { Link } from 'react-router';
import { connect } from 'react-redux';
import { getCourses } from '../actions/course';


class Course extends React.Component {

componentDidMount() {
this.props.onGetCourses();
}

allCourses() {
console.log(this.props.onGetCourses());
return this.props.courses.map((course) => {
return(
<li>{ course.name }</li>
);
});

return this.props
}

render() {
return (
<div>
<ul>
{ this.allCourses() }
</ul>

</div>
)
}
}

const mapStateToProps = (state) => {
return {
courses: state.course.courses
}
}

const mapDispatchToProps = (dispatch) => {
return {
onGetCourses: () => dispatch(getCourses)
}
}

export default connect(mapStateToProps, mapDispatchToProps)(Course);


I tried this but it doesn't work.

Course Reducer

const initialState = {
courses: []
};



export default function course(state= initialState, action) {

switch (action.type) {
case 'GET_COURSES':
return Object.assign({}, state, {
courses: action.courses
})
default:
return state;
}


}

Answer

First, onGetCourses: () => dispatch(getCourses) should be changed to onGetCourses: () => dispatch(getCourses()) (you need to actually invoke the action creator).

When it comes to where you should call the action, it is absolutely fine to do it in componentDidMount, as you have done.