Skip to content

Getting Todo Items from Backend

In order to be able to communicate with backend we will use fetch library that is built in any modern browser. You can find more here https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch.

First, we will make a new action getTodos that will call our GET endpoint on backend, get the data and dispatch action to update our store.

export function addItem(title: string) {
    return {
        type: 'ADD_ITEM',
        title
    }
}

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.' });
        }
    };
}