I want to build a function in React + Redux that, when a user clicks a button, calls an API and loads the data into the store, then display the data on a page.
I want to use the redux-actions
framework: https://redux-actions.js.org/ but I'm a little confused about different examples I've seen.
In some examples I see the following:
export const GET_USER_DATA = 'GET_USER_DATA';
export const getUserData = createAction(
GET_USER_DATA,
async () => {
try {
return await getUserInfo(config);
} catch (error) {
console.log("Error occurred");
}
},
);
and then I've seen other examples that use dispatch
like this (taken from: https://codeburst.io/redux-actions-through-example-part-3-91dc41ebe4be):
const fetchPhraseRequest = createAction('PHRASE_FETCH_REQUEST');
const fetchPhraseResponse = createAction('PHRASE_FETCH_RESPONSE');
export const clearPhrase = createAction('PHRASE_CLEAR');
export const fetchPhrase = () => (dispatch) => {
dispatch(fetchPhraseRequest());
fromAPI.getPhrase()
.then((value) => {
dispatch(fetchPhraseResponse(value));
})
.catch((err) => {
dispatch(fetchPhraseResponse(err));
});
};
I'm new to React and Redux and am trying to understand why/when you would do one or the other..
A question I have about the first example:
- without calling dispatch
, will a reducer be able to act on this action? If so, how does this work without calling dispatch?