Reputation: 111
I'm new in Redux. Can somebody explain, how can I get request data from Get
componentDidMount() {
axios.get('/api/v3/products', {
params: {
pageNumber: 1,
pageSize: 500,
}
})
.then(response => {
this.setState({result: response.data});
})
.catch(function (error) {
console.log('error TestMethod', error);
})
.then(function () {
// always executed
});
}
And place it in store in Redux
const initState = {
products: [
{id: 1, title: 'first'},
{id: 2, title: 'second'},
{id: 3, title: 'third'},
{id: 4, title: 'fourth'},
{id: 5, title: 'fifth'},
],
};
Are there any methods?
Upvotes: 0
Views: 754
Reputation: 2970
You need to use middleware to handle this type of redux side effects. You can use either redux-thunk or redux-saga
redux-thunk documentation explains Why Do I Need This
Thunks are the recommended middleware for basic Redux side effects logic, including complex synchronous logic that needs access to the store, and simple async logic like AJAX requests.
You can also use redux-saga which does the similar task.
Upvotes: 1
Reputation: 2309
Inside reducer place a case in switch say...
case FETCH_DATA: {
return {...state, data: action.payload}
}
Now you have reducer code in place. Inside then block dispatch action {type:FETCH_DATA, payload:response.data}
.then(response => {
this.setState({result: response.data});
})
Upvotes: 1