Below is the code for my action creator:
export function fetchPosts()
{
const request = axios.get(`${ROOT_URL}/posts${API_KEY}`);
return
{
As per redux documentation:
Actionsare plain JavaScript objects. Actions must have atype propertythat indicates the type of action being performed. Types should typically be defined asstring constants. Once your app is large enough, you may want to move them into a separate module.
And Action Creators
Action creators are functions that create actions
In Redux action creators simply return an action:
function addTodo(text) { return { type: ADD_TODO, text } }
So when you call the action creator from your component through dispatch your action creator just needs to simply return a plain javascript object.
So a normal action creator will be
export function fetchPosts()
{
return
{
type: FETCH_POSTS;
payload: "somevalue"
};
}
Now if you want to call APIs within your action creators you need to make use of middlewares like redux-thunk or redux-saga while creating a store
like
import thunk from 'redux-thunk';
const store = createStore(reducers, applyMiddleware(thunk));
You you configure your store with middleware you can modify your actions to
export function fetchPosts() {
return (dispatch) => {
axios.get(`${ROOT_URL}/posts${API_KEY}`)
.then((response)=> {
dispatch( {
type: FETCH_POSTS,
payload: request
})
})
}
}
As per the redux-thunk documentation
Why Do you need redux-thunk?
Redux Thunk middlewareallows you to write action creators that return a function instead of an action. The thunk can be used to delay thedispatchof an action, or todispatchonly if a certain condition is met. The inner function receives the store methodsdispatch and getStateasparameters.