Reputation: 135
I tried to use useEffect for fetching data from API with useDispatch hook:
const dispatch = useDispatch();
useEffect(() => {dispatch(actions.fetchSearch(submitValue))}, [submitValue, dispatch]);
Where submitValue - it is an input value for search query. fetchSearch() looks like this:
export const fetchSearch = (query) => {
return dispatch => {
const queryParams = 'http://190.75.199.65/api/products?count=20&sort_by=numberOfEntries&sort_order=DESC&page=1&search='+query;
axios.get(queryParams)
.then( res=> {
dispatch(fetchSearchSuccess(res.data));
}
)
};
};
I can fetch data by this code, but an error occured all the time:
An effect function must not return anything besides a function, which is used for clean-up.
It looks like you wrote useEffect(async () => ...) or returned a Promise. Instead, write the async function inside your effect and call it immediately
I tried to make async function inside useEffect, but error is same or maybe I make something wrong.
Upvotes: 1
Views: 1356
Reputation: 135
code work without any changes
const dispatch = useDispatch();
useEffect(() => {dispatch(actions.fetchSearch(submitValue))}, [submitValue, dispatch]);
just forgot to remove old useEffect.
Upvotes: 0
Reputation: 315
try to do this:
const dispatch = useDispatch();
useEffect(() => {
(async () => {
await dispatch(actions.fetchSearch(submitValue));
})();
}, [submitValue, dispatch]);
I think it is because you are directly calling a async function and it is returning a promise in useEffect.
Upvotes: 1