How to make AJAX request in Redux?
You can use redux-thunk middleware which allows you to define async actions.
Let’s take an example of fetching specific account as an AJAX call using fetch API:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | export function fetchAccount(id) { return dispatch => { dispatch(setLoadingAccountState()) // Show a loading spinner fetch(`/account/${id}`, (response) => { dispatch(doneFetchingAccount()) // Hide loading spinner if (response.status === 200) { dispatch(setAccount(response.json)) // Use a normal function to set the received state } else { dispatch(someError) } }) } } function setAccount(data) { return { type: 'SET_Account', data: data } } |
If you like this question & answer and want to contribute, then write your question & answer and email to freewebmentor[@]gmail.com. Your question and answer will appear on FreeWebMentor.com and help other developers.