aws-amplify#Storage TypeScript Examples
The following examples show how to use
aws-amplify#Storage.
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example #1
Source File: App.tsx From Rapid-Application-Development-with-AWS-Amplify with MIT License | 4 votes |
App = () => {
const defaultPostState = { id: "", title: "", content: "", image: "" };
// Post
const [postState, setPostState] = useState(defaultPostState);
const [posts, setPosts] = useState([]);
// Create post section
const [createSectionState, setCreateSectionState] = useState(true);
// Update post section
const [updateSectionState, setUpdateSectionState] = useState(false);
//image upload
const [img, setImg] = useState("");
useEffect(() => {
fetchPosts();
}, []);
const urlToBlob = async (url:string) => {
return new Promise((resolve, reject) => {
var xhr = new XMLHttpRequest();
xhr.onerror = reject;
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) {
resolve(xhr.response);
}
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
})
}
const onImageUploadChange = async () => {
try {
let imageFile = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
allowsEditing: true,
aspect: [4, 3],
quality: 0.1,
});
if (!imageFile.cancelled) {
const file: any = imageFile.uri;
const fileName: any = file.replace(/^.*[\\\/]/, "");
const contentType: any = fileName.split(".").pop().toLowerCase();
setInput("image", fileName);
const response = await urlToBlob(file);
Storage.put(fileName, response, {
contentType: "image/" + contentType,
})
.then(async (result: any) => {
console.log("result.key", result.key);
setImg((await Storage.get(result.key)) as string);
console.log("onImageUploadChange result:", result);
})
.catch((err) => console.error(err));
}
console.log("onImageUploadChange imageFile:", imageFile);
} catch (err) {
console.error("onImageUploadChange err:", err);
}
};
const fetchPosts = async (): Promise<any> => {
try {
console.log("fetching posts");
const postData: any = await API.graphql(
graphqlOperation(queries.listPosts)
);
const posts: any = postData.data.listPosts.items;
setPosts(posts);
} catch (err) {
console.log("error fetching posts: ", err);
}
};
const createSubscription: any = API.graphql(
graphqlOperation(subscriptions.onCreatePost)
);
createSubscription.subscribe({
next: (postData: any) => {
console.log("onCreatePost", postData);
fetchPosts();
},
});
const updateSubscription: any = API.graphql(
graphqlOperation(subscriptions.onUpdatePost)
);
updateSubscription.subscribe({
next: (postData: any) => {
console.log("onUpdatePost", postData);
fetchPosts();
},
});
const deleteSubscription: any = API.graphql(
graphqlOperation(subscriptions.onDeletePost)
);
deleteSubscription.subscribe({
next: (postData: any) => {
console.log("onDeletePost", postData);
fetchPosts();
},
});
const setInput = (key: any, value: any): any => {
setPostState({ ...postState, [key]: value });
};
const createPost = async (): Promise<any> => {
try {
if (!postState.title || !postState.content) return;
const post = { ...postState };
console.log("creating post", post);
const result = await API.graphql(
graphqlOperation(mutations.createPost, {
input: {
title: post.title,
content: post.content,
image: post.image,
},
})
);
setPosts([...posts, post] as SetStateAction<never[]>);
setPostState(defaultPostState);
console.log("created post", result);
} catch (err) {
console.log("error creating post:", err);
}
};
const updatePost = async (): Promise<any> => {
try {
if (!postState.title || !postState.content) return;
const post = { ...postState };
console.log("updating post", post);
const result = await API.graphql(
graphqlOperation(mutations.updatePost, {
input: {
id: post.id,
title: post.title,
content: post.content,
},
})
);
setUpdateSectionState(false);
setCreateSectionState(true);
console.log("updated post", result);
setPostState(defaultPostState);
} catch (err) {
console.log("error updating post:", err);
}
};
const deletePost = async (postID: string): Promise<any> => {
try {
if (!postID) return;
console.log("deleting post", postID);
const result = await API.graphql(
graphqlOperation(mutations.deletePost, {
input: {
id: postID,
},
})
);
console.log("deleted post", result);
} catch (err) {
console.log("error deleting post:", err);
}
};
const findPosts = async (title: string): Promise<any> => {
try {
console.log("finding posts:", title);
const postData: any = await API.graphql(
graphqlOperation(queries.listPosts, {
filter: {
title: {
contains: title,
},
},
})
);
console.log("found posts:");
const posts: any = postData.data.listPosts.items;
setPosts(posts);
} catch (err) {
console.log("error finding posts ", err);
}
};
return (
<SafeAreaView style={styles.safeArea}>
<View style={styles.container}>
<TextInput
onChangeText={(val) => findPosts(val)}
style={styles.input}
placeholder="Search"
/>
{createSectionState ? (
<View>
<Text style={styles.title}>Create Post</Text>
<View>
<Text
style={styles.button}
onPress={() => {
onImageUploadChange();
}}
>
Pick an image from camera roll
</Text>
{img ? (
<Image
source={{ uri: img }}
style={{ width: 320, height: 200 }}
/>
) : null}
</View>
<TextInput
onChangeText={(val) => setInput("title", val)}
style={styles.input}
value={postState.title}
placeholder="Title"
/>
<TextInput
onChangeText={(val) => setInput("content", val)}
style={styles.textArea}
value={postState.content}
placeholder="Content"
/>
<Text style={styles.button} onPress={createPost}>
Create Post
</Text>
</View>
) : null}
{updateSectionState ? (
<View>
<Text style={styles.title}>Update Post</Text>
<TextInput
onChangeText={(val) => setInput("title", val)}
style={styles.input}
value={postState.title}
placeholder="Title"
/>
<TextInput
onChangeText={(val) => setInput("content", val)}
style={styles.textArea}
value={postState.content}
placeholder="Content"
/>
<Text style={styles.button} onPress={updatePost}>
Update Post
</Text>
</View>
) : null}
<ScrollView style={styles.scrollView}>
{posts.map((post: any, index: any) => (
<View key={post.id ? post.id : index} style={styles.post}>
<S3Image style={styles.postImage} level="public" imgKey={post.image} />
<Text style={styles.postTitle}>
{post.title}
</Text>
<Text style={styles.postContent}>{post.content}</Text>
<View style={{ flexDirection: "row" }}>
<Text
style={styles.postUpdate}
onPress={() => {
setPostState(post);
setUpdateSectionState(true);
setCreateSectionState(false);
}}
>
Update
</Text>
<Text
style={styles.postDelete}
onPress={() => {
deletePost(post.id);
}}
>
Delete
</Text>
</View>
</View>
))}
</ScrollView>
<StatusBar style="auto" />
</View>
</SafeAreaView>
);
}
Example #2
Source File: App.tsx From Rapid-Application-Development-with-AWS-Amplify with MIT License | 4 votes |
App = () => {
const defaultPostState = { id: "", title: "", content: "", image: "" };
// Post
const [postState, setPostState] = useState(defaultPostState);
const [posts, setPosts] = useState([]);
// Create post section
const [createSectionState, setCreateSectionState] = useState(true);
// Update post section
const [updateSectionState, setUpdateSectionState] = useState(false);
//image upload
const [img, setImg] = useState("");
const onImageUploadChange = (event: any) => {
const file = event.target.files[0];
const fileName = file.name;
const contentType = fileName.split(".").pop().toLowerCase();
console.log("fileName", fileName);
setInput("image", fileName as string);
Storage.put(fileName, file, {
contentType: "image/" + contentType,
})
.then(async (result: any) => {
console.log("result.key", result.key);
setImg((await Storage.get(result.key)) as string);
})
.catch((err) => console.error(err));
};
useEffect(() => {
fetchPosts();
}, []);
const fetchPosts = async (): Promise<any> => {
try {
console.log("fetching posts");
const postData: any = await API.graphql(
graphqlOperation(queries.listPosts)
);
const posts: any = postData.data.listPosts.items;
setPosts(posts);
} catch (err) {
console.log("error fetching posts: ", err);
}
};
const createSubscription: any = API.graphql(
graphqlOperation(subscriptions.onCreatePost)
);
createSubscription.subscribe({
next: (postData: any) => {
console.log("onCreatePost", postData);
fetchPosts();
},
});
const updateSubscription: any = API.graphql(
graphqlOperation(subscriptions.onUpdatePost)
);
updateSubscription.subscribe({
next: (postData: any) => {
console.log("onUpdatePost", postData);
fetchPosts();
},
});
const deleteSubscription: any = API.graphql(
graphqlOperation(subscriptions.onDeletePost)
);
deleteSubscription.subscribe({
next: (postData: any) => {
console.log("onDeletePost", postData);
fetchPosts();
},
});
const setInput = (key: any, value: any): any => {
setPostState({ ...postState, [key]: value });
};
const refresh = () => {
window.location.reload();
};
const createPost = async (): Promise<any> => {
try {
if (!postState.title || !postState.content) return;
const post = { ...postState };
console.log("creating post", post);
const result = await API.graphql(
graphqlOperation(mutations.createPost, {
input: {
title: post.title,
content: post.content,
image: post.image,
},
})
);
setPosts([...posts, post] as SetStateAction<never[]>);
setPostState(defaultPostState);
console.log("created post", result);
} catch (err: any) {
console.log("error creating post:", err);
}
};
const updatePost = async (): Promise<any> => {
try {
if (!postState.title || !postState.content) return;
const post = { ...postState };
console.log("updating post", post);
const result = await API.graphql(
graphqlOperation(mutations.updatePost, {
input: {
id: post.id,
title: post.title,
content: post.content,
image: post.image,
},
})
);
setUpdateSectionState(false);
setCreateSectionState(true);
console.log("updated post", result);
setPostState(defaultPostState);
refresh();
} catch (err: any) {
console.log("error updating post:", err);
}
};
const deletePost = async (postID: string): Promise<any> => {
try {
if (!postID) return;
console.log("deleting post", postID);
const result = await API.graphql(
graphqlOperation(mutations.deletePost, {
input: {
id: postID,
},
})
);
console.log("deleted post", result);
refresh();
} catch (err: any) {
console.log("error deleting post:", err);
}
};
const findPosts = async (title: string): Promise<any> => {
try {
console.log("finding posts:", title);
const postData: any = await API.graphql(
graphqlOperation(queries.listPosts, {
filter: {
title: {
contains: title,
},
},
})
);
console.log("found posts:");
const posts: any = postData.data.listPosts.items;
setPosts(posts);
} catch (err) {
console.log("error finding posts ", err);
}
};
return (
<div>
<div className="container">
<input
className="find"
type="search"
onChange={(event) => findPosts(event.target.value)}
placeholder="Find post by title"
/>
{createSectionState === true ? (
<section className="create-section">
<h2>Create Post</h2>
{img && <img src={img} alt={img}></img>}
<input
type="file"
accept="image/*"
onChange={(event) => onImageUploadChange(event)}
/>
<input
onChange={(event) => setInput("title", event.target.value)}
value={postState.title}
placeholder="Title"
/>
<textarea
onChange={(event) => setInput("content", event.target.value)}
value={postState.content}
placeholder="Content"
/>
<button className="create-button" onClick={createPost}>
Create
</button>
</section>
) : null}
{updateSectionState === true ? (
<section className="update-section">
<h2>Update Post</h2>
{img && <img src={img} alt={img}></img>}
<input
type="file"
accept="image/*"
onChange={(event) => onImageUploadChange(event)}
/>
<input
onChange={(event) => setInput("title", event.target.value)}
value={postState.title}
placeholder="Title"
/>
<textarea
onChange={(event) => setInput("content", event.target.value)}
value={postState.content}
placeholder="Content"
/>
<button className="create-button" onClick={updatePost}>
Update
</button>
</section>
) : null}
{posts.map((post: any, index: any) => (
<div key={post.id ? post.id : index} className="post">
<AmplifyS3Image imgKey={post.image} />
<label className="post-title">{post.title}</label>
<p className="post-content">{post.content}</p>
<button
className="update-button"
onClick={() => {
setPostState(post);
setCreateSectionState(false);
setUpdateSectionState(true);
}}
>
Update
</button>
<button
className="delete-button"
onClick={() => {
deletePost(post.id);
}}
>
Delete
</button>
</div>
))}
</div>
</div>
);
}
Example #3
Source File: App.tsx From Rapid-Application-Development-with-AWS-Amplify with MIT License | 4 votes |
App = () => {
LogBox.ignoreAllLogs();
const defaultPostState = {id: '', title: '', content: '', image: ''};
// Post
const [postState, setPostState] = useState(defaultPostState);
const [posts, setPosts] = useState([]);
// Create post section
const [createSectionState, setCreateSectionState] = useState(true);
// Update post section
const [updateSectionState, setUpdateSectionState] = useState(false);
//image upload
const [img, setImg] = useState('');
const urlToBlob = async (url:string) => {
return new Promise((resolve, reject) => {
var xhr = new XMLHttpRequest();
xhr.onerror = reject;
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) resolve(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
})
}
const onImageUploadChange = async ():Promise<void> => {
try {
const options: ImageLibraryOptions = {
mediaType: 'photo',
quality: 0.1,
maxWidth: 400,
maxHeight: 300
};
launchImageLibrary(options, async (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.errorCode) {
console.log('ImagePicker Error: ', response.errorMessage);
} else {
// You can also display the image using data:
// const source = { uri: 'data:image/jpeg;base64,' + response.data };
setImg(response.uri as string);
if (response.uri as string) {
const file: any = response.uri;
const fileName: any = file.replace(/^.*[\\\/]/, '');
const contentType: any = fileName.split('.').pop().toLowerCase();
setInput("image", fileName);
const responseData = await urlToBlob(file);
Storage.put(fileName, responseData, {
contentType: 'image/' + contentType,
})
.then(async (result: any) => {
console.log('result.key', result.key);
setImg((await Storage.get(result.key)) as string);
console.log('onImageUploadChange result:', result);
//setInput('image', img);
})
.catch((err) => console.error(err));
}
console.log('onImageUploadChange img:', img);
}
});
} catch (err) {
console.error('onImageUploadChange err:', err);
}
};
useEffect(():void => {
fetchPosts();
}, []);
const fetchPosts = async (): Promise<void> => {
try {
console.log('fetching posts');
const postData: any = await API.graphql(
graphqlOperation(queries.listPosts),
);
const posts: any = postData.data.listPosts.items;
setPosts(posts);
} catch (err) {
console.log('error fetching posts: ', err);
}
};
const createSubscription: any = API.graphql(
graphqlOperation(subscriptions.onCreatePost),
);
createSubscription.subscribe({
next: (postData: any) => {
console.log('onCreatePost', postData);
fetchPosts();
},
});
const updateSubscription: any = API.graphql(
graphqlOperation(subscriptions.onUpdatePost),
);
updateSubscription.subscribe({
next: (postData: any) => {
console.log('onUpdatePost', postData);
fetchPosts();
},
});
const deleteSubscription: any = API.graphql(
graphqlOperation(subscriptions.onDeletePost),
);
deleteSubscription.subscribe({
next: (postData: any) => {
console.log('onDeletePost', postData);
fetchPosts();
},
});
const setInput = (key: any, value: any): any => {
setPostState({...postState, [key]: value});
};
const createPost = async (): Promise<any> => {
try {
if (!postState.title || !postState.content) return;
const post = {...postState};
console.log('creating post', post);
const result = await API.graphql(
graphqlOperation(mutations.createPost, {
input: {
title: post.title,
content: post.content,
image: post.image,
},
}),
);
setPosts([...posts, post] as SetStateAction<never[]>);
setPostState(defaultPostState);
console.log('created post', result);
} catch (err: any) {
console.log('error creating post:', err);
}
};
const updatePost = async (): Promise<any> => {
try {
if (!postState.title || !postState.content) return;
const post = {...postState};
console.log('updating post', post);
const result = await API.graphql(
graphqlOperation(mutations.updatePost, {
input: {
id: post.id,
title: post.title,
content: post.content,
image: post.image,
},
}),
);
setUpdateSectionState(false);
setCreateSectionState(true);
console.log('updated post', result);
setPostState(defaultPostState);
} catch (err: any) {
console.log('error updating post:', err);
}
};
const deletePost = async (postID: string): Promise<any> => {
try {
if (!postID) return;
console.log('deleting post', postID);
const result = await API.graphql(
graphqlOperation(mutations.deletePost, {
input: {
id: postID,
},
}),
);
console.log('deleted post', result);
} catch (err: any) {
console.log('error deleting post:', err);
}
};
const findPosts = async (title: string): Promise<any> => {
try {
console.log('finding posts:', title);
const postData: any = await API.graphql(
graphqlOperation(queries.listPosts, {
filter: {
title: {
contains: title,
},
},
}),
);
console.log('found posts:');
const posts: any = postData.data.listPosts.items;
setPosts(posts);
} catch (err) {
console.log('error finding posts ', err);
}
};
return (
<SafeAreaView style={styles.safeArea}>
<View style={styles.container}>
<TextInput
onChangeText={(val) => findPosts(val)}
style={styles.input}
placeholder="Search"
/>
{createSectionState ? (
<View>
<Text style={styles.title}>Create Post</Text>
<View>
<Text
style={styles.button}
onPress={() => {
onImageUploadChange();
}}>
Pick an image from camera roll
</Text>
{img ? (
<Image source={{uri: img}} style={{width: 320, height: 200}} />
) : null}
</View>
<TextInput
onChangeText={(val) => setInput('title', val)}
style={styles.input}
value={postState.title}
placeholder="Title"
/>
<TextInput
onChangeText={(val) => setInput('content', val)}
style={styles.textArea}
value={postState.content}
placeholder="Content"
/>
<Text style={styles.button} onPress={createPost}>
Create Post
</Text>
</View>
) : null}
{updateSectionState ? (
<View>
<Text style={styles.title}>Update Post</Text>
<TextInput
onChangeText={(val) => setInput('title', val)}
style={styles.input}
value={postState.title}
placeholder="Title"
/>
<TextInput
onChangeText={(val) => setInput('content', val)}
style={styles.textArea}
value={postState.content}
placeholder="Content"
/>
<Text style={styles.button} onPress={updatePost}>
Update Post
</Text>
</View>
) : null}
<ScrollView style={styles.scrollView}>
{posts.map((post: any, index: any) => (
<View key={post.id ? post.id : index} style={styles.post}>
<S3Image style={styles.postImage} level="public" imgKey={post.image} />
<Text style={styles.postTitle}>{post.title} {post.image}</Text>
<Text style={styles.postContent}>{post.content}</Text>
<View style={{flexDirection: 'row'}}>
<Text
style={styles.postUpdate}
onPress={() => {
setPostState(post);
setUpdateSectionState(true);
setCreateSectionState(false);
}}>
Update
</Text>
<Text
style={styles.postDelete}
onPress={() => {
deletePost(post.id);
}}>
Delete
</Text>
</View>
</View>
))}
</ScrollView>
</View>
</SafeAreaView>
);
}
Example #4
Source File: App.tsx From Rapid-Application-Development-with-AWS-Amplify with MIT License | 4 votes |
App = () => {
const defaultPostState = { id: "", title: "", content: "", image: "" };
// Post
const [postState, setPostState] = useState(defaultPostState);
const [posts, setPosts] = useState([]);
// Create post section
const [createSectionState, setCreateSectionState] = useState(true);
// Update post section
const [updateSectionState, setUpdateSectionState] = useState(false);
//image upload
const [img, setImg] = useState("");
const onImageUploadChange = (event: any) => {
const file = event.target.files[0];
const fileName = file.name;
const contentType = fileName.split(".").pop().toLowerCase();
console.log("fileName", fileName);
setInput("image", fileName as string);
Storage.put(fileName, file, {
contentType: "image/" + contentType,
})
.then(async (result: any) => {
console.log("result.key", result.key);
setImg((await Storage.get(result.key)) as string);
})
.catch((err) => console.error(err));
};
useEffect(() => {
fetchPosts();
}, []);
const fetchPosts = async (): Promise<any> => {
try {
console.log("fetching posts");
const postData: any = await API.graphql(
graphqlOperation(queries.listPosts)
);
const posts: any = postData.data.listPosts.items;
setPosts(posts);
} catch (err) {
console.log("error fetching posts: ", err);
}
};
const createSubscription: any = API.graphql(
graphqlOperation(subscriptions.onCreatePost)
);
createSubscription.subscribe({
next: (postData: any) => {
console.log("onCreatePost", postData);
fetchPosts();
},
});
const updateSubscription: any = API.graphql(
graphqlOperation(subscriptions.onUpdatePost)
);
updateSubscription.subscribe({
next: (postData: any) => {
console.log("onUpdatePost", postData);
fetchPosts();
},
});
const deleteSubscription: any = API.graphql(
graphqlOperation(subscriptions.onDeletePost)
);
deleteSubscription.subscribe({
next: (postData: any) => {
console.log("onDeletePost", postData);
fetchPosts();
},
});
const setInput = (key: any, value: any): any => {
setPostState({ ...postState, [key]: value });
};
const refresh = () => {
window.location.reload();
};
const createPost = async (): Promise<any> => {
try {
if (!postState.title || !postState.content) return;
const post = { ...postState };
console.log("creating post", post);
const result = await API.graphql(
graphqlOperation(mutations.createPost, {
input: {
title: post.title,
content: post.content,
image: post.image,
},
})
);
setPosts([...posts, post] as SetStateAction<never[]>);
setPostState(defaultPostState);
console.log("created post", result);
} catch (err: any) {
console.log("error creating post:", err);
}
};
const updatePost = async (): Promise<any> => {
try {
if (!postState.title || !postState.content) return;
const post = { ...postState };
console.log("updating post", post);
const result = await API.graphql(
graphqlOperation(mutations.updatePost, {
input: {
id: post.id,
title: post.title,
content: post.content,
image: post.image,
},
})
);
setUpdateSectionState(false);
setCreateSectionState(true);
console.log("updated post", result);
setPostState(defaultPostState);
refresh();
} catch (err: any) {
console.log("error updating post:", err);
}
};
const deletePost = async (postID: string): Promise<any> => {
try {
if (!postID) return;
console.log("deleting post", postID);
const result = await API.graphql(
graphqlOperation(mutations.deletePost, {
input: {
id: postID,
},
})
);
console.log("deleted post", result);
refresh();
} catch (err: any) {
console.log("error deleting post:", err);
}
};
const findPosts = async (title: string): Promise<any> => {
try {
console.log("finding posts:", title);
const postData: any = await API.graphql(
graphqlOperation(queries.listPosts, {
filter: {
title: {
contains: title,
},
},
})
);
console.log("found posts:");
const posts: any = postData.data.listPosts.items;
setPosts(posts);
} catch (err) {
console.log("error finding posts ", err);
}
};
return (
<div>
<div className="container">
<input
className="find"
type="search"
onChange={(event) => findPosts(event.target.value)}
placeholder="Find post by title"
/>
{createSectionState === true ? (
<section className="create-section">
<h2>Create Post</h2>
{img && <img src={img} alt={img}></img>}
<input
type="file"
accept="image/*"
onChange={(event) => onImageUploadChange(event)}
/>
<input
onChange={(event) => setInput("title", event.target.value)}
value={postState.title}
placeholder="Title"
/>
<textarea
onChange={(event) => setInput("content", event.target.value)}
value={postState.content}
placeholder="Content"
/>
<button className="create-button" onClick={createPost}>
Create
</button>
</section>
) : null}
{updateSectionState === true ? (
<section className="update-section">
<h2>Update Post</h2>
{img && <img src={img} alt={img}></img>}
<input
type="file"
accept="image/*"
onChange={(event) => onImageUploadChange(event)}
/>
<input
onChange={(event) => setInput("title", event.target.value)}
value={postState.title}
placeholder="Title"
/>
<textarea
onChange={(event) => setInput("content", event.target.value)}
value={postState.content}
placeholder="Content"
/>
<button className="create-button" onClick={updatePost}>
Update
</button>
</section>
) : null}
{posts.map((post: any, index: any) => (
<div key={post.id ? post.id : index} className="post">
<AmplifyS3Image imgKey={post.image} />
<label className="post-title">{post.title}</label>
<p className="post-content">{post.content}</p>
<button
className="update-button"
onClick={() => {
setPostState(post);
setCreateSectionState(false);
setUpdateSectionState(true);
}}
>
Update
</button>
<button
className="delete-button"
onClick={() => {
deletePost(post.id);
}}
>
Delete
</button>
</div>
))}
</div>
</div>
);
}
Example #5
Source File: App.tsx From Rapid-Application-Development-with-AWS-Amplify with MIT License | 4 votes |
App = () => {
LogBox.ignoreAllLogs();
const defaultPostState = {id: '', title: '', content: '', image: ''};
// Post
const [postState, setPostState] = useState(defaultPostState);
const [posts, setPosts] = useState([]);
// Create post section
const [createSectionState, setCreateSectionState] = useState(true);
// Update post section
const [updateSectionState, setUpdateSectionState] = useState(false);
//image upload
const [img, setImg] = useState('');
const urlToBlob = async (url:string) => {
return new Promise((resolve, reject) => {
var xhr = new XMLHttpRequest();
xhr.onerror = reject;
xhr.onreadystatechange = () => {
if (xhr.readyState === 4) resolve(xhr.response);
};
xhr.open('GET', url);
xhr.responseType = 'blob';
xhr.send();
})
}
const onImageUploadChange = async ():Promise<void> => {
try {
const options: ImageLibraryOptions = {
mediaType: 'photo',
quality: 0.1,
maxWidth: 400,
maxHeight: 300
};
launchImageLibrary(options, async (response) => {
console.log('Response = ', response);
if (response.didCancel) {
console.log('User cancelled image picker');
} else if (response.errorCode) {
console.log('ImagePicker Error: ', response.errorMessage);
} else {
// You can also display the image using data:
// const source = { uri: 'data:image/jpeg;base64,' + response.data };
setImg(response.uri as string);
if (response.uri as string) {
const file: any = response.uri;
const fileName: any = file.replace(/^.*[\\\/]/, '');
const contentType: any = fileName.split('.').pop().toLowerCase();
setInput("image", fileName);
const responseData = await urlToBlob(file);
Storage.put(fileName, responseData, {
contentType: 'image/' + contentType,
})
.then(async (result: any) => {
console.log('result.key', result.key);
setImg((await Storage.get(result.key)) as string);
console.log('onImageUploadChange result:', result);
//setInput('image', img);
})
.catch((err) => console.error(err));
}
console.log('onImageUploadChange img:', img);
}
});
} catch (err) {
console.error('onImageUploadChange err:', err);
}
};
useEffect(():void => {
fetchPosts();
}, []);
const fetchPosts = async (): Promise<void> => {
try {
console.log('fetching posts');
const postData: any = await API.graphql(
graphqlOperation(queries.listPosts),
);
const posts: any = postData.data.listPosts.items;
setPosts(posts);
} catch (err) {
console.log('error fetching posts: ', err);
}
};
const createSubscription: any = API.graphql(
graphqlOperation(subscriptions.onCreatePost),
);
createSubscription.subscribe({
next: (postData: any) => {
console.log('onCreatePost', postData);
fetchPosts();
},
});
const updateSubscription: any = API.graphql(
graphqlOperation(subscriptions.onUpdatePost),
);
updateSubscription.subscribe({
next: (postData: any) => {
console.log('onUpdatePost', postData);
fetchPosts();
},
});
const deleteSubscription: any = API.graphql(
graphqlOperation(subscriptions.onDeletePost),
);
deleteSubscription.subscribe({
next: (postData: any) => {
console.log('onDeletePost', postData);
fetchPosts();
},
});
const setInput = (key: any, value: any): any => {
setPostState({...postState, [key]: value});
};
const createPost = async (): Promise<any> => {
try {
if (!postState.title || !postState.content) return;
const post = {...postState};
console.log('creating post', post);
const result = await API.graphql(
graphqlOperation(mutations.createPost, {
input: {
title: post.title,
content: post.content,
image: post.image,
},
}),
);
setPosts([...posts, post] as SetStateAction<never[]>);
setPostState(defaultPostState);
console.log('created post', result);
} catch (err: any) {
console.log('error creating post:', err);
}
};
const updatePost = async (): Promise<any> => {
try {
if (!postState.title || !postState.content) return;
const post = {...postState};
console.log('updating post', post);
const result = await API.graphql(
graphqlOperation(mutations.updatePost, {
input: {
id: post.id,
title: post.title,
content: post.content,
image: post.image,
},
}),
);
setUpdateSectionState(false);
setCreateSectionState(true);
console.log('updated post', result);
setPostState(defaultPostState);
} catch (err: any) {
console.log('error updating post:', err);
}
};
const deletePost = async (postID: string): Promise<any> => {
try {
if (!postID) return;
console.log('deleting post', postID);
const result = await API.graphql(
graphqlOperation(mutations.deletePost, {
input: {
id: postID,
},
}),
);
console.log('deleted post', result);
} catch (err: any) {
console.log('error deleting post:', err);
}
};
const findPosts = async (title: string): Promise<any> => {
try {
console.log('finding posts:', title);
const postData: any = await API.graphql(
graphqlOperation(queries.listPosts, {
filter: {
title: {
contains: title,
},
},
}),
);
console.log('found posts:');
const posts: any = postData.data.listPosts.items;
setPosts(posts);
} catch (err) {
console.log('error finding posts ', err);
}
};
return (
<SafeAreaView style={styles.safeArea}>
<View style={styles.container}>
<TextInput
onChangeText={(val) => findPosts(val)}
style={styles.input}
placeholder="Search"
/>
{createSectionState ? (
<View>
<Text style={styles.title}>Create Post</Text>
<View>
<Text
style={styles.button}
onPress={() => {
onImageUploadChange();
}}>
Pick an image from camera roll
</Text>
{img ? (
<Image source={{uri: img}} style={{width: 320, height: 200}} />
) : null}
</View>
<TextInput
onChangeText={(val) => setInput('title', val)}
style={styles.input}
value={postState.title}
placeholder="Title"
/>
<TextInput
onChangeText={(val) => setInput('content', val)}
style={styles.textArea}
value={postState.content}
placeholder="Content"
/>
<Text style={styles.button} onPress={createPost}>
Create Post
</Text>
</View>
) : null}
{updateSectionState ? (
<View>
<Text style={styles.title}>Update Post</Text>
<TextInput
onChangeText={(val) => setInput('title', val)}
style={styles.input}
value={postState.title}
placeholder="Title"
/>
<TextInput
onChangeText={(val) => setInput('content', val)}
style={styles.textArea}
value={postState.content}
placeholder="Content"
/>
<Text style={styles.button} onPress={updatePost}>
Update Post
</Text>
</View>
) : null}
<ScrollView style={styles.scrollView}>
{posts.map((post: any, index: any) => (
<View key={post.id ? post.id : index} style={styles.post}>
<S3Image style={styles.postImage} level="public" imgKey={post.image} />
<Text style={styles.postTitle}>{post.title} {post.image}</Text>
<Text style={styles.postContent}>{post.content}</Text>
<View style={{flexDirection: 'row'}}>
<Text
style={styles.postUpdate}
onPress={() => {
setPostState(post);
setUpdateSectionState(true);
setCreateSectionState(false);
}}>
Update
</Text>
<Text
style={styles.postDelete}
onPress={() => {
deletePost(post.id);
}}>
Delete
</Text>
</View>
</View>
))}
</ScrollView>
</View>
</SafeAreaView>
);
}
Example #6
Source File: NewTweetScreen.tsx From TwitterClone with MIT License | 4 votes |
export default function NewTweetScreen() {
const [tweet, setTweet] = useState("");
const [imageUrl, setImageUrl] = useState("");
const navigation = useNavigation();
const getPermissionAsync = async () => {
if (Platform.OS !== 'web') {
const { status } = await Permissions.askAsync(Permissions.CAMERA_ROLL);
if (status !== 'granted') {
alert('Sorry, we need camera roll permissions to make this work!');
}
}
};
useEffect(() => {
getPermissionAsync()
}, [])
const pickImage = async () => {
try {
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.All,
allowsEditing: true,
aspect: [4, 3],
quality: 1,
});
if (!result.cancelled) {
setImageUrl(result.uri);
}
console.log(result);
} catch (E) {
console.log(E);
}
};
const uploadImage = async () => {
try {
const response = await fetch(imageUrl);
const blob = await response.blob();
const urlParts = imageUrl.split('.');
const extension = urlParts[urlParts.length - 1];
const key = `${uuidv4()}.${extension}`;
await Storage.put(key, blob);
return key;
} catch (e) {
console.log(e);
}
return '';
}
const onPostTweet = async () => {
let image;
if (!!imageUrl) {
image = await uploadImage();
}
try {
const currentUser = await Auth.currentAuthenticatedUser({ bypassCache: true });
const newTweet = {
content: tweet,
image,
userID: currentUser.attributes.sub,
}
await API.graphql(graphqlOperation(createTweet, { input: newTweet }));
navigation.goBack();
} catch (e) {
console.log(e);
}
}
return (
<SafeAreaView style={styles.container}>
<View style={styles.headerContainer}>
<TouchableOpacity onPress={() => navigation.goBack()}>
<AntDesign name="close" size={30} color={Colors.light.tint} />
</TouchableOpacity>
<TouchableOpacity style={styles.button} onPress={onPostTweet}>
<Text style={styles.buttonText}>Tweet</Text>
</TouchableOpacity>
</View>
<View style={styles.newTweetContainer}>
<ProfilePicture image={'https://scontent.fkiv3-1.fna.fbcdn.net/v/t31.0-8/s960x960/22256588_1932617800312085_5686197942193420542_o.jpg?_nc_cat=110&_nc_sid=85a577&_nc_ohc=svjjE7DUkc0AX9yjcdC&_nc_ht=scontent.fkiv3-1.fna&tp=7&oh=1df4116c73c45a32ebad070704ca3333&oe=5F6ECD77'}/>
<View style={styles.inputsContainer}>
<TextInput
value={tweet}
onChangeText={(value) => setTweet(value)}
multiline={true}
numberOfLines={3}
style={styles.tweetInput}
placeholder={"What's happening?"}
/>
<TouchableOpacity onPress={pickImage}>
<Text style={styles.pickImage}>Pick a image</Text>
</TouchableOpacity>
<Image source={{ uri: imageUrl }} style={styles.image} />
</View>
</View>
</SafeAreaView>
);
}