export interface Tag { id: string; name: string; } export interface TagWithColor extends…
- User
export interface Tag { id: string; name: string; } export interface TagWithColor extends Tag { color: string; }
const colors = ["#FFE9B8", "#D0E9D7", "#D6E6FF"];
interface TagsSlice { tags: TagWithColor[];
}
const initialState: TagsSlice = { tags: [],
};
export const tagsSlice = createSlice({ name: "tagsSlice", initialState, reducers: { setTags(state, action: PayloadAction<TagWithColor[]>) { state.tags = action.payload; },
в setTags сразу сделаем определение цвета и будем в редаксе хранить теги уже с их цветами. И для определения цвета использовать id % 3, 3 здесь это кол-во доступных цветов
- Assistant
export interface Tag { id: string; name: string; }
export interface TagWithColor extends Tag { color: string; }
const colors = ["#FFE9B8", "#D0E9D7", "#D6E6FF"];
interface TagsSlice { tags: TagWithColor[]; }
const initialState: TagsSlice = { tags: [], };
export const tagsSlice = createSlice({ name: "tagsSlice", initialState, reducers: { setTags(state, action: PayloadAction<Tag[]>) { state.tags = action.payload.map((tag, index) => ({ ...tag, color: colors[index % colors.length] })); }, }, });
codeIn the `setTags` reducer, I have modified the `action.payload` to be of type `Tag[]` instead of `TagWithColor[]`. Then, I map over the `action.payload` and assign each tag a color based on its index using the modulo operator `%`. This way, the tags will be stored in Redux with their respective colors.