-
Notifications
You must be signed in to change notification settings - Fork 0
/
App.js
98 lines (90 loc) · 2.67 KB
/
App.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
import { useEffect, useState } from 'react';
import { useFonts } from 'expo-font';
import { View, ScrollView, StyleSheet } from 'react-native';
import Word from './components/Word';
import Button from './components/Button';
import { API_KEY } from '@env'
export default function App() {
const apiKey = API_KEY;
const [fontsLoaded] = useFonts({
'Athletics': require('./assets/Athletics.otf'),
});
const [word, setWord] = useState(null)
const [definition, setDefinition] = useState(null)
const [loading, setLoading] = useState(true)
const [definitionLoading, setDefinitionLoading] = useState(false);
const options = {
method: 'GET',
headers: {
'X-Api-Key': apiKey,
},
};
// Function to fetch a new word
const fetchNewWord = () => {
setLoading(true);
setDefinition(null);
fetch('https://api.api-ninjas.com/v1/randomword', options)
.then((resp) => resp.json())
.then((data) => {
setWord(data.word);
setLoading(false);
})
.catch((error) => {
console.log(error);
setLoading(false);
});
};
// Function to fetch the definition for the current word
const fetchWordDefinition = (currentWord) => {
setDefinitionLoading(true);
fetch(`https://api.api-ninjas.com/v1/dictionary?word=${currentWord}`, options)
.then((resp) => resp.json())
.then((data) => {
if (data.definition) {
setDefinition(data.definition)
} else {
setDefinition("I don't have a definition for this word yet. Can you help me out by googling it?");
}
})
.catch((error) => console.log(error))
.finally(() => setDefinitionLoading(false));
};
useEffect(() => {
fetchNewWord(); // Fetch a new word on initial render
}, []);
useEffect(() => {
if (word) {
fetchWordDefinition(word); // Fetch the definition when word changes
}
}, [word]);
if (!fontsLoaded) {
return null;
}
return (
<View style={styles.container}>
<ScrollView showsVerticalScrollIndicator={false} style={styles.textContainer}>
{/* As long as either the word or its definition have not yet rendered, the activity indicator will be shown: */}
<Word word={word} definition={definition} loading={loading || definitionLoading} />
</ScrollView>
<View style={styles.buttonContainer}>
<Button fetchNewWord={fetchNewWord} />
</View>
</View>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#052E31',
paddingLeft: 30,
paddingRight: 30,
paddingBottom: 20
},
textContainer: {
},
buttonContainer: {
position: 'sticky',
bottom: 0,
backgroundColor: '#052E31',
}
});