Skip to content

Adding New Todo Item to Backend

To let user add items to the database, we will first modify and existing action addItem that will call our POST endpoint on backend, get the data and dispatch action to update our store and add item to the list.

export function addItem(title: string) {
    return async (dispatch: any) => {
        try {
            const addTodoItem: any = await fetch('http://localhost:3001/todo', {
                method: 'POST',
                headers: {
                    'Content-Type': 'application/json',
                },
                body: JSON.stringify({
                    title,
                })
            });

            const body = await addTodoItem.json();

            if (addTodoItem.status !== 200) {
                return dispatch({ type: 'ADD_ITEM_ERROR', message: body.message });
            }

            return dispatch({ type: 'ADD_ITEM_SUCCESS', item: body.todo });
        } catch (error) {
            return dispatch({ type: 'ADD_ITEM_ERROR', message: 'Something went wrong.' });
        }
    };
}

export function removeItem(item_id: number) {
    return {
        type: 'REMOVE_ITEM',
        item_id
    }
}

export function markItemAsDone(item_id: number) {
    return {
        type: 'MARK_ITEM_DONE',
        item_id
    }
}

export function getTodos() {
    return async (dispatch: any) => {
        try {
            const todoList: any = await fetch('http://localhost:3001/todos', {
                method: 'GET'
            });

            const body = await todoList.json();

            if (todoList.status !== 200) {
                return dispatch({ type: 'GET_TODOS_ERROR', message: body.message });
            }

            return dispatch({ type: 'GET_TODOS_SUCCESS', items: body.data });
        } catch (error) {
            return dispatch({ type: 'GET_TODOS_ERROR', message: 'Something went wrong.' });
        }
    };
}
We will now have 2 action types for adding a new item