I think my question for a while seems to be a duplicate but i guess it is not, i have checked many questions that have same title but with different case
The problem is that i was forced to use react hook twice in my code and i even think to make them three but i feel that a bad practice and i am sure there is a work around or a solution for that
I have data that i want to initially fetch and i implemented that by first useEffect call, the data can be filtered or sorted later and i have filters checkboxes and a select for sort queries, checking a checkbox will filter data and selecting an option will sort it, i am using redux and react-redux connect method to create the state tree which includes filters and sortBy
//the first call
useEffect(() => {
loadProducts();
}, []);
//the second call
useEffect(() => {
loadProducts(filters, sortBy)
}, [filters, sortBy])
const mapStateToProps = (state) => ({
filters: state.filters,
sortBy: state.sortBy
});
const mapDispatchToProps = (dispatch) => ({
loadProducts: (filters, sortBy) => {
fetch('certain API').then(res => res.json()).then(json => {
dispatch(fetchProducts(json.products, filters, sortBy));
}).catch(err => 'error fetching data');
}
});
Now the first call is to initially retrieve data from API, loadProducts function doesn't need any arguments, and the second one is when doing filtering or sorting and the function in this case needs the arguments and it works when any of filters or sortBy get changed
I even think to make them three calls by dividing the second call into two calls like this:
useEffect(() => {
loadProducts(filters)
}, [filters])
useEffect(() => {
loadProducts(undefined, sortBy)
}, [sortBy])
and that's because i do not want to make filtering and sorting happening every time even when only one of them should work, because i think sorting will work also when the user only fiters data and vice versa.
This is my fetchProducts action:
import { filterProducts, sortProducts } from './../../util/util';
export const fetchProducts = (products, filters, sortBy) => {
if (filters && filters.length) {
products = filterProducts(products, filters);
}
if (sortBy) {
sortProducts(products, sortBy);
}
return {
type: FETCH_PRODUCTS,
payload: products
}
}