Skip to content

Commit

Permalink
[#11] feat: implement api fetch
Browse files Browse the repository at this point in the history
  • Loading branch information
hee-suh committed Mar 23, 2022
1 parent 1a6870c commit d80b59b
Show file tree
Hide file tree
Showing 3 changed files with 97 additions and 29 deletions.
49 changes: 30 additions & 19 deletions react-native/components/BottomDrawer.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,22 +5,23 @@ import { Popover, Button, Text, Modal, FormControl, Input, VStack, Select, Check
import { theme } from '../core/theme';
import type { BottomDrawerProps, EventForm, UserData } from '../types';
import { useAuth } from '../contexts/Auth';
import { useNavigation, StackActions } from '@react-navigation/native';


const highlight = (text: string, registered: boolean) =>
<Text fontFamily="body" fontWeight={700} fontStyle="normal" fontSize='md' pt={24} style={!registered ? styles.highlighted : styles.grayBackground}>{text}</Text>
let date = new Date();

function BottomDrawer(props: BottomDrawerProps) {
const [currentEvent, setCurrentEvent] = useState<number>(0);
const [openSaveForm, setOpenSaveForm] = useState<boolean>(false);
const [resultsTitle, setResultsTitle] = useState<string>('title');
const [openEventForm, setOpenEventForm] = useState<boolean>(false);
const [eventForm, setEventForm] = useState<EventForm>({title: '', date: '', cId: 1, description: ''});
const [eventForm, setEventForm] = useState<EventForm>({cId: 1, title: '', date: '', description: ''});
// TEST: mockup data
const [user, setUser] = useState<UserData>({uid: 1, uprofileImg: 1, username: 'hee', ulanguage: 'ko', uchildren: [{cid: 1, cname: 'soo', color: 1}, {cid: 2, cname: 'joo', color: 3}]})
// const [user, setUser] = useState<UserData>();
const auth = useAuth();
const navigation = useNavigation();

useEffect(()=> {
// setUser(auth?.userData);
Expand All @@ -47,19 +48,8 @@ function BottomDrawer(props: BottomDrawerProps) {
const closePopup = () => {
setCurrentEvent(0);
}

const handleOpenSaveForm = (prop?: string) => {
if (prop==='save') {
// TODO: fetch api
// data 보내고, success 라면, 서버에 저장된 제목 받아와서 보여주기!
let data = {
id: props?.results?.id,
title: resultsTitle,
date: date.getFullYear()+'-'+(date.getMonth()+1)+'-'+date.getDate()
}
console.log(data);
Alert.alert(`The result was saved in Search as [${resultsTitle}]`)
}

const handleOpenSaveForm = () => {
if (openSaveForm) {
setResultsTitle('title');
}
Expand All @@ -75,8 +65,31 @@ function BottomDrawer(props: BottomDrawerProps) {

const addEvent = () => {
// TODO: fetch api
// TEST
let status = "success";

if (auth?.authData?.jwt_token && eventForm) {
fetch("http://localhost:8080/notice/calendar", {
method: 'POST',
headers: {
'JWT_TOKEN': auth.authData.jwt_token
},
body: JSON.stringify(eventForm),
redirect: 'follow'
})
.then(response => response.json())
.then(data => status = data)
.catch(function (error) {
console.log(error.response.status) // 401
console.log(error.response.data.error) //Please Authenticate or whatever returned from server
if(error.response.status==401) {
//redirect to login
Alert.alert("The session has expired. Please log in again.");
auth.signOut();
navigation.dispatch(StackActions.popToTop())
}
});
}

switch (status) {
case "success":
Alert.alert("The event has been successfully added to your calendar!");
Expand Down Expand Up @@ -129,9 +142,7 @@ function BottomDrawer(props: BottomDrawerProps) {
}}>
Cancel
</Button>
<Button onPress={() => {
handleOpenSaveForm('save')
}}>
<Button onPress={() => props?.saveResults && props.saveResults(resultsTitle)}>
Save
</Button>
</Button.Group>
Expand Down
73 changes: 65 additions & 8 deletions react-native/screens/TranslateScreen.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,15 @@ import { useToast, Box } from 'native-base';
import mime from "mime";
import * as ImagePicker from 'expo-image-picker';
import { useAuth } from '../contexts/Auth';
import { StackActions } from '@react-navigation/native';

/* TODO:
- 스크롤 내려가게 하기 (지금은 ScrollView의 스크롤이 안 먹음)
- low highlight 주기 (지금은 텍스트 높이만큼 background에 색 줘서 highlight)
*/

const date = new Date();

export default function TranslateScreen({ navigation }: Navigation) {
const [hasPermission, setHasPermission] = useState<boolean>(false);
const [fontsLoaded, SetFontsLoaded] = useState<boolean>(false);
Expand Down Expand Up @@ -113,18 +116,27 @@ export default function TranslateScreen({ navigation }: Navigation) {
if (auth?.authData?.jwt_token) {
fetch("http://localhost:8080/notice/ocr", {
method: 'POST',
headers: { 'Authorization': auth.authData.jwt_token },
headers: {
'JWT_TOKEN': auth.authData.jwt_token
},
body: formdata,
redirect: 'follow'
})
.then(response => response.text()) // TODO: response.json()
.then(data => console.log(data)) // TODO: setResults(data)
.catch(error => console.log('error', error));
.then(response => response.json())
.then(data => setResults(data))
.catch(function (error) {
console.log(error.response.status) // 401
console.log(error.response.data.error) //Please Authenticate or whatever returned from server
if(error.response.status==401) {
//redirect to login
Alert.alert("The session has expired. Please log in again.");
auth.signOut();
navigation.dispatch(StackActions.popToTop())
}
});
}

// TEST: mockup data
setResults({
id: 1,
fullText: [
{id: 1, content: "1. Schedule of the closing ceremony and diploma presentation ceremony: Friday, January 4, 2019 at 9 o'clock for students to go to school.\n1) ", date: "", highlight: false, registered: false},
{id: 2, content: "Closing ceremony", date: "2022-01-04", highlight: true, registered: false},
Expand All @@ -148,9 +160,54 @@ export default function TranslateScreen({ navigation }: Navigation) {
setShowKorean(!showKorean);
}

const saveResults = (): void => {
const saveResults = (title: string): void => {
// TODO: api
Alert.alert("The scanned result was saved in <Search>.");
// TODO: fetch api
// data 보내고, success 라면, 서버에 저장된 제목 받아와서 보여주기!
if (!title) {
Alert.alert("You must enter at least one character for the title.");
return;
}

if (imageUri) {
let FormData = require('form-data');
const formdata = new FormData();
formdata.append('uploadfile', {
uri : imageUri,
type: mime.getType(imageUri),
name: imageUri.split("/").pop()
});
let data = {
'title': title,
'date': date.getFullYear()+'-'+(date.getMonth()+1)+'-'+date.getDate(),
'fullText': results?.fullText,
'korean': results?.korean
}
formdata.append('noticeRequestDTO', new Blob([JSON.stringify(data)], {type: 'application/json'}));

if (auth?.authData?.jwt_token) {
fetch('http://localhost:8080/notice/ocr', {
method: 'POST',
headers: {
'JWT_TOKEN': auth.authData.jwt_token
},
body: formdata,
redirect: 'follow'
})
.then(response => response.json())
.then(data => Alert.alert(`The result was saved in Search as [${data?.title}]`))
.catch(function (error) {
console.log(error.response.status) // 401
console.log(error.response.data.error) //Please Authenticate or whatever returned from server
if(error.response.status==401) {
//redirect to login
Alert.alert("The session has expired. Please log in again.");
auth.signOut();
navigation.dispatch(StackActions.popToTop())
}
});
}
}
}

const closeResults = (): void => {
Expand Down
4 changes: 2 additions & 2 deletions react-native/types.ts
Original file line number Diff line number Diff line change
Expand Up @@ -66,7 +66,7 @@ interface Event {
}

interface Result {
id: number,
id?: number,
imageUri?: string,
fullText: Event[],
korean: string
Expand All @@ -86,7 +86,7 @@ interface BottomDrawerProps {
isFullDrawer?: boolean,
isTranslateScreen?: boolean,
handleKorean?: () => void,
saveResults?: () => void,
saveResults?: (title: string) => void,
closeResults?: () => void,
retakePicture?: () => void,
}
Expand Down

0 comments on commit d80b59b

Please sign in to comment.