1
- import { Fragment } from "react" ;
1
+ import { Fragment , useEffect , useRef , useState } from "react" ;
2
2
import { useSelector , useDispatch } from "react-redux" ;
3
3
4
4
import { setLoading } from "../store/" ;
5
+ import { setSearchResult } from "../store/searchSlice" ;
5
6
import styles from "../styles/Header.module.css" ;
7
+ import { fetchMealByName } from "../thunk/fetchMealByName" ;
8
+
9
+ const DEFAULT_STATUS_TEXT = `Type a Dish Name to Search for it's ingredient` ;
6
10
7
11
const Header = ( ) => {
8
- const loading = useSelector ( ( { app } ) => app ) ;
12
+ const { loading } = useSelector ( ( { app } ) => app ) ;
13
+ const [ statusText , setStatusText ] = useState ( null ) ;
14
+
15
+ useEffect ( ( ) => {
16
+ setStatusText ( DEFAULT_STATUS_TEXT ) ;
17
+ } , [ ] ) ;
18
+
19
+ useEffect ( ( ) => {
20
+ setStatusText ( ( prevState ) => ( loading ? "Loading" : prevState ) ) ;
21
+ } , [ loading ] ) ;
22
+
23
+ const searchInput = useRef ( ) ;
9
24
const actionDispatcher = useDispatch ( ) ;
10
25
11
26
const setLoadingTo = ( status ) => {
12
27
if ( typeof status === "boolean" ) actionDispatcher ( setLoading ( status ) ) ;
13
28
} ;
14
29
30
+ const searchMealAPI = async ( ) => {
31
+ try {
32
+ if ( searchInput . current . value . trim ( ) . length !== 0 ) {
33
+ setLoadingTo ( true ) ;
34
+ const searchResult = await fetchMealByName ( searchInput . current . value ) ;
35
+ if ( searchResult !== null ) {
36
+ actionDispatcher ( setSearchResult ( searchResult ) ) ;
37
+ setStatusText ( "" ) ;
38
+ } else setStatusText ( "No data has been recieved" ) ;
39
+ }
40
+ } catch ( error ) {
41
+ console . error ( error ) ;
42
+ } finally {
43
+ setLoadingTo ( false ) ;
44
+ }
45
+ } ;
15
46
return (
16
47
< Fragment >
17
48
< h1 className = { styles . app_heading } > Recipe Finder</ h1 >
@@ -20,11 +51,17 @@ const Header = () => {
20
51
type = "text"
21
52
placeholder = "Enter the Name of the Dish"
22
53
className = { styles . input_recipe }
54
+ ref = { searchInput }
23
55
/>
24
- < button onClick = { ( ) => setLoadingTo ( true ) } > Get Ingredients</ button >
25
- < p className = { styles . search_comment } >
26
- Type a Dish Name to Search for it's ingredient
27
- </ p >
56
+ < button
57
+ onClick = { ( ) => {
58
+ setLoadingTo ( true ) ;
59
+ searchMealAPI ( ) ;
60
+ } }
61
+ >
62
+ Get Ingredients
63
+ </ button >
64
+ < p className = { styles . search_comment } > { statusText } </ p >
28
65
</ span >
29
66
</ Fragment >
30
67
) ;
0 commit comments