Home > Software engineering >  How to flat array in zustand
How to flat array in zustand

Time:09-19

I have a brands list array, every brand object has a brand name & products

So the first time, I pushed the new brand object to the brands list, and that's work well,

Now if I want to push a new brand to the brands list and keep the previous brand data it does not work as expected.

and it looks like this

issue

the expected should be like this

expected

I'm trying to use flat() but not work here

minimal reproduction here

Code

import create from 'zustand';
import {persist} from 'zustand/middleware';
import {zustandStorage} from '../utils/Storage';

export const useFavoritesStore = create(
  persist(
    set => ({
      brandsFavoritesList: [],
      updateFavList: brandData => {
        set(state => ({
          brandsFavoritesList:
            // check if there are any brands on the list before
            state.brandsFavoritesList.length > 0
              ? state.brandsFavoritesList.map(brand =>
                  // if the brand exists before pushing new products
                  brand.tenant === brandData?.tenant
                    ? {
                        ...brand,
                        products: [...brand.products, ...brandData.products],
                      }
                    : // if the brand does not exist before push the new brand data to the brandsFavoritesList 
    // Issue here...
                      [...state.brandsFavoritesList, brandData].flat(),
                )
              : [...state.brandsFavoritesList, {...brandData}],
        }));
      },
    }),
    {
      name: 'favorites-local',
      getStorage: () => zustandStorage,
    },
  ),
);

CodePudding user response:

It looks like you want something like

function updateBrandsFavoritesList(brandsFavoritesList, brandData) {
  const brandIndex = brandsFavoritesList.findIndex((brand) => brand.tenant === brandData.tenant);
  if (brandIndex < 0) {
    // This is a new brand, append it to the list.
    return [...brandsFavoritesList, brandData];
  }
  // This is an existing brand, update it.
  const existingBrand = brandsFavoritesList[brandIndex];
  const updatedBrand = {
    ...existingBrand,
    products: [...existingBrand.products, ...brandData.products],
  };
  return brandsFavoritesList.map((brand, index) => (index === brandIndex ? updatedBrand : brand));
}

const updateFavList = (brandData) => {
  if (!brandData) return;
  set(({brandsFavoritesList}) => ({
    brandsFavoritesList: updateBrandsFavoritesList(brandsFavoritesList, brandData),
  }));
}

– no need for flat.

The complex logic of finding and updating a brand has been moved to a separate free function which should be easier to e.g. test in isolation too.

(Even better still would be to use TypeScript so errors would be more obvious...)

  • Related