1. Anuncie Aqui ! Entre em contato fdantas@4each.com.br

How to give a unique ID to new item in NGRX reducer?

Discussão em 'Angular' iniciado por Snorlax, Setembro 27, 2024 às 17:13.

  1. Snorlax

    Snorlax Guest

    I have a simple todo list that seems to work fine but I'm not sure I'm implementing the part where I'm adding a new item with a unique ID using Math.random() to the todo list properly. I want to give it a unique ID basically and then when deleting it, find that value, is the way I'm doing it fine?

    export interface TodoState {
    todos: Todo[];
    }

    export const initialState: TodoState = {
    todos: [
    {
    id: 1,
    task: '1',
    description: 'description 1',
    completed: false,
    },
    {
    id: 2,
    task: '2',
    description: 'description 2',
    completed: false,
    },
    ],

    };

    export const todoReducer = createReducer(
    initialState,
    on(TodoActions.addTodo, (state, { text }) => ({
    ...state,
    todos: [
    ...state.todos,
    {
    id: Math.random(), // id: state.todos.length + 1
    task: '' + Math.random() + '',
    description: text,
    completed: false,
    },
    ],
    })),
    on(TodoActions.resetTodo, () => initialState)
    );


    Stackblitz: Link

    Continue reading...

Compartilhe esta Página