mardi 27 août 2019

which is better in the term of performance and best pratice?(react - redux)

I am creating an E-commerce website using react and redux, it shows all products in home page then show all products again in another page but with options of filtering and sorting.

I asked here a question two days ago asking about the best way to process data (filtering and sorting) here

The answers went for doing the data processing after fetching data and fetch data again when filtering and sorting query changes then again process data instead of fetching once and doing data processing in the reducers.

Now as i described my website above, i need to show all products in home page and adding the feature of filtering and sorting data in another page and my mind goes for creating two requests one in home page and second in the other page using fetch function using the same API link and i can add filtering and sorting functionality in an action different from one related to home page products.

Code:

const mapDispatchToProps = (dispatch) => {
  return {
    loadProducts: () => {
      fetch(productsAPI).then(res => res.json()).then(json =>
        dispatch(fetchProducts(json.products))).catch(err => 'error fetching data')
    }
  };
}


action.js: (all products in home page)

const fetchAllProducts = (allProducts) => {(
  type: FETCH_ALL_PRODUCTS,
  payload: allProducts
)} 


action.js: (products in the other page)

const fetchProducts = (allProducts, filter, sortBy) => {
    let products;


    if (filters && filters.length > 0) {
        products = filters.map(f => allProducts.filter(p => p.category === f)).reduce((acc, cur) => [...acc, ...cur], []);
    }

    if (sortBy) {
        if (sortBy === 'low to high price') {
           products.sort((a, b) => a.newPrice - b.newPrice);
        }

        if (sortBy === 'high to low price') {
            products.sort((a, b) => a.newPrice - b.newPrice)
        }
    }

    return {
        type: FETCH_PRODUCTS,
        payload: products
    }
}

Now what is the better way to do that in the term of performance and best practice, i think processing data in a reducer would be acceptable in that case or should i make two requests one for every page???




Aucun commentaire:

Enregistrer un commentaire