Last active
April 20, 2020 09:48
-
-
Save mikehibm/9b644145680882a38aa16fa47950a859 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { API, Auth } from 'aws-amplify'; | |
const apiName = 'amplifytest01api'; | |
const apiPath = '/todos'; | |
const userIdPrefix = 'user:'; | |
const defaultOptions = { | |
headers: {}, | |
response: true, | |
}; | |
export async function loadTodos(dispatch) { | |
dispatch({ type: 'beginAsync' }); | |
const user = await Auth.currentUserInfo(); | |
if (!user) { | |
dispatch({ type: 'loadTodos', payload: [] }); | |
return; | |
} | |
try { | |
const userId = user.id; | |
const path = `${apiPath}/${userIdPrefix}${userId}`; | |
const res = await API.get(apiName, path, defaultOptions); | |
const todos = res.data; | |
dispatch({ type: 'loadTodos', payload: todos }); | |
} catch (error) { | |
dispatch({ type: 'error', payload: error }); | |
} | |
} | |
export async function addTodo(dispatch, text) { | |
dispatch({ type: 'beginAsync' }); | |
const user = await Auth.currentUserInfo(); | |
if (!user) { | |
dispatch({ type: 'loadTodos', payload: [] }); | |
return; | |
} | |
try { | |
const path = `${apiPath}`; | |
const options = { | |
...defaultOptions, | |
body: { | |
text, | |
done: false, | |
}, | |
}; | |
await API.post(apiName, path, options); | |
await loadTodos(dispatch); | |
} catch (error) { | |
dispatch({ type: 'error', payload: error }); | |
} | |
} | |
export async function updateTodo(dispatch, todo) { | |
dispatch({ type: 'beginAsync' }); | |
const user = await Auth.currentUserInfo(); | |
if (!user) { | |
dispatch({ type: 'loadTodos', payload: [] }); | |
return; | |
} | |
try { | |
const userId = user.id; | |
const path = `${apiPath}/${userIdPrefix}${userId}/${todo.id}`; | |
const options = { | |
...defaultOptions, | |
body: { | |
text: todo.text, | |
done: todo.done, | |
}, | |
}; | |
await API.put(apiName, path, options); | |
await loadTodos(dispatch); | |
} catch (error) { | |
console.error(error); | |
dispatch({ type: 'error', payload: error }); | |
} | |
} | |
export async function deleteTodo(dispatch, todo) { | |
dispatch({ type: 'beginAsync' }); | |
const user = await Auth.currentUserInfo(); | |
if (!user) { | |
dispatch({ type: 'loadTodos', payload: [] }); | |
return; | |
} | |
try { | |
const userId = user.id; | |
const path = `${apiPath}/${userIdPrefix}${userId}/${todo.id}`; | |
const options = { | |
...defaultOptions, | |
}; | |
await API.del(apiName, path, options); | |
await loadTodos(dispatch); | |
} catch (error) { | |
console.error(error); | |
dispatch({ type: 'error', payload: error }); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment