(Partial) Photo picker for new posts

This commit is contained in:
Adolfo Reyna
2022-11-22 08:44:17 -05:00
parent 5cf38ae6d3
commit 5ff2c7971f
3 changed files with 181 additions and 28 deletions

View File

@@ -1,13 +1,67 @@
import React, { useState } from 'react';
import { View, StyleSheet } from 'react-native';
import { View, StyleSheet, Image } from 'react-native';
import { TextInput, Button } from 'react-native-paper';
import API from './../API.js';
import { useNavigation } from '@react-navigation/native';
import * as ImagePicker from 'expo-image-picker';
let NewPost = ({profileid, newPostCB}) => {
let NewPost = ({ profileid, newPostCB }) => {
let [postContent, setPostContent] = useState('');
const navigation = useNavigation();
const [photo, setPhoto] = React.useState(null);
const pickImage = async () => {
// No permissions request is necessary for launching the image library
let result = await ImagePicker.launchImageLibraryAsync({
mediaTypes: ImagePicker.MediaTypeOptions.Images,
//allowsEditing: true,
//aspect: [4, 3],
//quality: 1,
allowsMultipleSelection: true,
});
if (!result.cancelled) {
setPhoto(result);
await handleUploadPhoto(result);
}
};
const handleUploadPhoto = async (photo) => {
if (!photo) return;
const uri =
Platform.OS === "android"
? photo.uri
: photo.uri.replace("file://", "");
const filename = photo.uri.split("/").pop();
const match = /\.(\w+)$/.exec(filename);
const ext = match?.[1];
const type = match ? `image/${match[1]}` : `image`;
const formData = new FormData();
formData.append("banner", {
uri,
name: `image.${ext}`,
type,
});
try {
fetch("https://social.emmint.com/upload.php", {
method: "POST",
body: formData,
headers: { "Content-Type": "multipart/form-data" }
})
.then((res) => res.json())
.then((data) => {
console.log(data);
return data.fileName;
})
.catch((err) => console.error(err));
} catch (err) {
console.log(err);
alert("Something went wrong");
}
};
return (
<View style={styles.newPost}>
@@ -20,16 +74,29 @@ let NewPost = ({profileid, newPostCB}) => {
/>
{
postContent ? (
<View style={{ flexDirection: "row", justifyContent: 'flex-end' }}>
<Button icon="add-a-photo" mode="outlined"></Button>
<Button icon="send" mode="outlined" onPress={() => {
setPostContent('');
API.newPost(postContent).then((newPost) => {
<>
<View style={{ flexDirection: "row", justifyContent: 'flex-end' }}>
<Button icon="add-a-photo" mode="outlined" onPress={pickImage} ></Button>
<Button icon="send" mode="outlined" onPress={() => {
setPostContent('');
if(newPostCB) newPostCB(newPost);
});
}}>Post</Button>
</View>
API.newPost(postContent).then((newPost) => {
setPostContent('');
if (newPostCB) newPostCB(newPost);
});
}}>Post</Button>
</View>
{photo && (
<View>
<Image
source={{ uri: photo.uri }}
style={{ width: 300, height: 300 }}
/>
<Button title="Upload Photo" onPress={handleUploadPhoto} />
</View>
)}
</>
) : undefined
}