Skip to content

Instantly share code, notes, and snippets.

@mikehibm
Last active April 20, 2020 09:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mikehibm/9b644145680882a38aa16fa47950a859 to your computer and use it in GitHub Desktop.
Save mikehibm/9b644145680882a38aa16fa47950a859 to your computer and use it in GitHub Desktop.
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