forked from dabit3/full-stack-react-native-appsync-workshop
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathhooks.js
More file actions
120 lines (106 loc) · 2.43 KB
/
hooks.js
File metadata and controls
120 lines (106 loc) · 2.43 KB
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
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
// query
import React, { useEffect, useReducer } from 'react'
const initialState = {
restaurants: [],
error: false
}
function reducer(state, action) {
switch (action.type) {
case 'set':
return {...state, restaurants: action.restaurants};
case 'error':
return { ...state, error: true}
default:
throw new Error();
}
}
async function fetchRestaurants(dispatch) {
try {
const restaurantData = await API.graphql(graphqlOperation(listRestaurants))
dispatch({
type: 'set',
restaurants: restaurantData.data.listRestaurants.items
})
} catch (err) {
dispatch({ type: 'error' })
}
}
// within the component
const [state, dispatch] = useReducer(reducer, initialState)
useEffect(() => {
fetchRestaurants(dispatch)
}, [])
state.restaurants.map((restaurant, index) => (
<Text key={index}>{restaurant.name}</Text>
))
// mutation
// First, update the a form state
const initialState = {
restaurants: [],
error: false,
name: '',
description: '',
city: ''
}
// update the reducer
function reducer(state, action) {
switch (action.type) {
case 'set':
return {...state, restaurants: action.restaurants};
case 'add':
return {
...state,
restaurants: [...state.restaurants, action.restaurant]
};
case 'updateInput':
return {
...state,
[action.inputType]: action.inputValue
}
case 'error':
return { ...state, error: true}
default:
throw new Error();
}
}
// Update form inputs
<TextInput
name='name'
value={this.state.name}
onChangeText={v => dispatch({
type: 'updateInput',
inputType: 'name',
inputValue: v
})}
/>
async function createRestaurant(dispatch, state) {
const { name, description, city } = state
const restaurant = {
name, description, city, clientId: CLIENTID
}
dispatch({
type: 'add',
restaurant
})
try {
await API.graphql(graphqlOperation(createRestaurant, {
input: restaurant
}))
console.log('item created!')
} catch (err) {
dispatch({
error: true,
})
}
}
// subscription
useEffect(() => {
const subscriber = API.graphql(graphqlOperation(onCreateRestaurant)).subscribe({
next: eventData => {
const restaurant = eventData.value.data.onCreateRestaurant
if(CLIENTID === restaurant.clientId) return
dispatch({ type: "add", restaurant })
}
})
return () => subscriber.unsubscribe()
}, [])