I've already checked StackOverflow.com and also the entire internet for a similar question and didn't find any, so please ignore and do not give a negative reputation if you find one as I need reputation in this moment of my life!
My code works fine but I would like to know why calling an API request inside the Action-Creator file is not a good practice and what is the replacement for it?
MyComponent.jsx
const MyComponent = () => {
dispatch = useDispatch();
return <div>
<button onClick={()=>{
dispatch(getItems("?color=xxx&manufacturer=yyy"));
}}></button>
</div>
}
ActionCreator.js
const getItems = (queryString) => async (dispatch) => {
try{
dispatch({
type: "FETCH_REQUEST",
});
// >>>>>> Here is the problem! <<<<<<
const response = await fetch("https://subname.name.com/api/" + queryString);
const data = await response.json();
dispatch({
type: "FETCH_SUCCESS",
payload: data,
});
}catch(error){
dispatch({
type: "FETCH_FAILURE",
payload: error,
});
}
}
Reducer.js
const INITIAL_STATE = {
items: [],
isLoading: false,
error: "",
};
const reducer = (currentState, action) => {
switch(action.type){
case: "FETCH_REQUEST":
return {
...currentState,
isLoading: true,
};
case: "FETCH_SUCCESS":
return {
...action.payload,
isLoading: false,
};
case: "FETCH_FAILURE":
return {
items: [],
error: "An error happend when fetching main data.",
};
}
}