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
the expected should be like this
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,
},
),
);

