frontend/Swit.js

64 lines
2.0 KiB
JavaScript
Raw Normal View History

2024-02-08 14:10:53 +00:00
import React, { useState } from 'react';
import { View, TextInput, Button, ActivityIndicator, Text, TouchableOpacity } from 'react-native';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { useTailwind } from 'tailwind-rn';
function SwitScreen({ navigation }) {
const [text, setText] = useState('');
const [loading, setLoading] = useState(false);
const [errorMessage, setErrorMessage] = useState('');
async function postTweet() {
try {
setLoading(true);
setErrorMessage(null); // Reset the error message before starting a new request
const token = await AsyncStorage.getItem('token');
const userID = await AsyncStorage.getItem('userID');
const apiUrl = await AsyncStorage.getItem('apiEndpoint')
const response = await fetch(`${apiUrl}/api/v1/app/swit/swits`, {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization': token,
},
body: JSON.stringify({ text }),
});
if (!response.ok) {
throw new Error(`Failed to post swit: ${response.status} ${await response.text()}`);
}
navigation.goBack();
} catch (error) {
console.error('Error:', error);
setErrorMessage(error.message);
} finally {
setLoading(false); // Put the setLoading in finally block so it will run whether there's an error or not
}
}
const tailwind = useTailwind();
return (
<View style={tailwind('p-4')}>
{errorMessage ? <Text style={tailwind('text-red-500 mb-2 text-center')}>{errorMessage}</Text> : null}
<TextInput
style={tailwind('border border-gray-500 p-2 mb-4')}
multiline
value={text}
onChangeText={setText}
/>
{/* if isLoading = true show activityindicator if not show below */}
{loading && <ActivityIndicator size="large" color="#0000ff" />}
<Button title="Post" onPress={postTweet} />
</View>
);
}
export default SwitScreen;