Files
EMI-ExpoAPP/components/NewPost.js
2022-11-22 08:44:17 -05:00

113 lines
3.6 KiB
JavaScript

import React, { useState } from 'react';
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 [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}>
<TextInput
label="New Post"
value={postContent}
onChangeText={setPostContent}
mode="outlined"
multiline={true}
/>
{
postContent ? (
<>
<View style={{ flexDirection: "row", justifyContent: 'flex-end' }}>
<Button icon="add-a-photo" mode="outlined" onPress={pickImage} ></Button>
<Button icon="send" mode="outlined" onPress={() => {
setPostContent('');
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
}
</View>
);
}
export default NewPost;
const styles = StyleSheet.create({
newPost: {
margin: 10
}
});