React Native
...
Data objects
Basic Operations
12 mnt
tutorial crud react native pendahuluan menyimpan data di parse dibangun di sekitar parse object parse object kelas setiap parse object parse object berisi pasangan kunci nilai dari data yang kompatibel dengan json data ini tidak memiliki skema, yang berarti anda tidak perlu menentukan sebelumnya kunci apa yang ada di setiap parse object parse object anda dapat dengan mudah menetapkan pasangan kunci nilai apa pun yang anda inginkan, dan backend kami akan menyimpannya anda juga dapat menentukan tipe data sesuai dengan kebutuhan aplikasi anda dan menyimpan tipe seperti angka angka , boolean boolean , string string , datetime datetime , daftar daftar , geopointers geopointers , dan objek objek , mengkodekannya ke json sebelum menyimpan parse juga mendukung penyimpanan dan kueri data relasional dengan menggunakan tipe pointers pointers dan relasi relasi dalam panduan ini, anda akan belajar bagaimana melakukan operasi data dasar melalui aplikasi contoh crud, yang akan menunjukkan kepada anda cara membuat, membaca, memperbarui, dan menghapus data dari database server parse anda di react native anda akan terlebih dahulu membuat fungsi komponen anda untuk setiap operasi crud, menggunakan mereka nanti dalam tata letak layar lengkap, yang menghasilkan aplikasi daftar tugas prasyarat untuk menyelesaikan tutorial ini, anda akan membutuhkan sebuah aplikasi react native yang dibuat dan terhubung ke back4app jika anda ingin menguji/menggunakan tata letak layar yang disediakan oleh panduan ini, anda harus mengatur react native paper react native paper perpustakaan tujuan untuk membangun aplikasi crud dasar di react native menggunakan parse 1 membuat objek data langkah pertama untuk mengelola data anda di database parse anda adalah memiliki beberapa data di dalamnya mari kita buat sebuah createtodo createtodo fungsi yang akan membuat sebuah instance baru dari parse object parse object dengan subclass “todo” todo akan memiliki sebuah judul( string string ) yang menggambarkan tugas dan sebuah field done( boolean boolean ) yang menunjukkan apakah tugas tersebut telah selesai javascript 1 const createtodo = async function () { 2 // this value comes from a state variable 3 const newtodotitlevalue = newtodotitle; 4 // creates a new todo parse object instance 5 let todo = new parse object('todo'); 6 todo set('title', newtodotitlevalue); 7 todo set('done', false); 8 // after setting the todo values, save it on the server 9 try { 10 await todo save(); 11 // success 12 alert alert('success!', 'todo created!'); 13 // refresh todos list to show the new one (you will create this function later) 14 readtodos(); 15 return true; 16 } catch (error) { 17 // error can be caused by lack of internet connection 18 alert alert('error!', error message); 19 return false; 20 }; 21 }; todolist tsx 1 const createtodo = async function () promise\<boolean> { 2 // this value comes from a state variable 3 const newtodotitlevalue string = newtodotitle; 4 // creates a new todo parse object instance 5 let todo parse object = new parse object('todo'); 6 todo set('title', newtodotitlevalue); 7 todo set('done', false); 8 // after setting the todo values, save it on the server 9 try { 10 await todo save(); 11 // success 12 alert alert('success!', 'todo created!'); 13 // refresh todos list to show the new one (you will create this function later) 14 readtodos(); 15 return true; 16 } catch (error) { 17 // error can be caused by lack of internet connection 18 alert alert('error!', error message); 19 return false; 20 }; 21 }; perhatikan bahwa jika database anda belum memiliki sebuah todo todo tabel (atau subclass) di dalamnya, parse akan membuatnya secara otomatis dan juga menambahkan kolom kolom yang diatur di dalam parse object parse object instance menggunakan parse object set() parse object set() metode, yang mengambil dua argumen nama field dan nilai yang akan diatur 2 membaca objek data setelah membuat beberapa data di database anda, aplikasi anda sekarang dapat membacanya dari server dan menampilkannya kepada pengguna anda silakan buat sebuah readtodos readtodos fungsi, yang akan melakukan sebuah parse query parse query , menyimpan hasilnya di dalam variabel state javascript 1 const readtodos = async function () { 2 // reading parse objects is done by using parse query 3 const parsequery = new parse query('todo'); 4 try { 5 let todos = await parsequery find(); 6 // be aware that empty or invalid queries return as an empty array 7 // set results to state variable 8 setreadresults(todos); 9 return true; 10 } catch (error) { 11 // error can be caused by lack of internet connection 12 alert alert('error!', error message); 13 return false; 14 }; 15 };1 const readtodos = async function () promise\<boolean> { 2 // reading parse objects is done by using parse query 3 const parsequery parse query = new parse query('todo'); 4 try { 5 let todos parse object\[] = await parsequery find(); 6 // be aware that empty or invalid queries return as an empty array 7 // set results to state variable 8 setreadresults(todos); 9 return true; 10 } catch (error) { 11 // error can be caused by lack of internet connection 12 alert alert('error!', error message); 13 return false; 14 }; 15 }; kelas parse query parse query sangat kuat, banyak batasan dan pengurutan dapat diterapkan pada kueri anda untuk saat ini, kita akan tetap pada kueri sederhana ini, yang akan mengambil setiap todo todo yang disimpan 3 memperbarui objek data memperbarui sebuah parse object parse object instance sangat mirip dengan membuat yang baru, kecuali bahwa dalam kasus ini, anda perlu menetapkan objectid objectid yang telah dibuat sebelumnya dan kemudian menyimpan, setelah mengatur nilai baru anda javascript 1 const updatetodo = async function (todoid, done) { 2 // create a new todo parse object instance and set todo id 3 let todo = new parse object('todo'); 4 todo set('objectid', todoid); 5 // set new done value and save parse object changes 6 todo set('done', done); 7 try { 8 await todo save(); 9 // success 10 alert alert('success!', 'todo updated!'); 11 // refresh todos list 12 readtodos(); 13 return true; 14 } catch (error) { 15 // error can be caused by lack of internet connection 16 alert alert('error!', error message); 17 return false; 18 }; 19 };1 const updatetodo = async function ( 2 todoid string, 3 done boolean, 4 ) promise\<boolean> { 5 // create a new todo parse object instance and set todo id 6 let todo parse object = new parse object('todo'); 7 todo set('objectid', todoid); 8 // set new done value and save parse object changes 9 todo set('done', done); 10 try { 11 await todo save(); 12 // success 13 alert alert('success!', 'todo updated!'); 14 // refresh todos list 15 readtodos(); 16 return true; 17 } catch (error) { 18 // error can be caused by lack of internet connection 19 alert alert('error!', error message); 20 return false; 21 }; 22 }; karena aplikasi contoh ini mewakili daftar tugas, fungsi pembaruan anda mengambil argumen tambahan, yaitu done done nilai, yang akan mewakili apakah tugas tertentu telah diselesaikan atau tidak 4 menghapus objek data untuk menghapus objek data, anda perlu memanggil destroy() destroy() metode di parse object parse object instance yang mewakilinya harap berhati hati karena operasi ini tidak dapat dibatalkan javascript 1 const deletetodo = async function (todoid) { 2 // create a new todo parse object instance and set todo id 3 const todo = new parse object('todo'); 4 todo set('objectid', todoid); 5 // destroy should be called to delete a parse object 6 try { 7 await todo destroy(); 8 alert alert('success!', 'todo deleted!'); 9 // refresh todos list to remove this one 10 readtodos(); 11 return true; 12 } catch (error) { 13 // error can be caused by lack of internet connection 14 alert alert('error!', error message); 15 return false; 16 }; 17 };1 const deletetodo = async function (todoid string) promise\<boolean> { 2 // create a new todo parse object instance and set todo id 3 let todo parse object = new parse object('todo'); 4 todo set('objectid', todoid); 5 // destroy should be called to delete a parse object 6 try { 7 await todo destroy(); 8 alert alert('success!', 'todo deleted!'); 9 // refresh todos list to remove this one 10 readtodos(); 11 return true; 12 } catch (error) { 13 // error can be caused by lack of internet connection 14 alert alert('error!', error message); 15 return false; 16 }; 17 }; mari kita gunakan sekarang empat fungsi ini dalam sebuah komponen lengkap, sehingga anda dapat mengujinya dan memastikan bahwa setiap operasi crud berfungsi dengan baik 5 menggunakan crud dalam komponen react native berikut adalah kode komponen lengkap, termasuk elemen antarmuka pengguna yang bergaya, variabel status, dan panggilan ke fungsi crud anda anda dapat membuat komponen terpisah dalam file yang disebut todolist js/todolist tsx todolist js/todolist tsx yang berisi kode berikut atau menambahkannya ke file aplikasi utama anda ( app js/app tsx app js/app tsx atau index js index js ) todolist js 1 import react, {usestate} from 'react'; 2 import { 3 alert, 4 view, 5 safeareaview, 6 image, 7 scrollview, 8 statusbar, 9 stylesheet, 10 touchableopacity, 11 } from 'react native'; 12 import parse from 'parse/react native'; 13 import { 14 list, 15 title, 16 iconbutton, 17 text as papertext, 18 button as paperbutton, 19 textinput as papertextinput, 20 } from 'react native paper'; 21	 22 export const todolist = () => { 23 // state variables 24 const \[readresults, setreadresults] = usestate(\[]); 25 const \[newtodotitle, setnewtodotitle] = usestate(''); 26	 27 // functions used by the screen components 28 const createtodo = async function () { 29 // this value comes from a state variable 30 const newtodotitlevalue = newtodotitle; 31 // creates a new todo parse object instance 32 let todo = new parse object('todo'); 33 todo set('title', newtodotitlevalue); 34 todo set('done', false); 35 // after setting the todo values, save it on the server 36 try { 37 await todo save(); 38 // success 39 alert alert('success!', 'todo created!'); 40 // refresh todos list to show the new one (you will create this function later) 41 readtodos(); 42 return true; 43 } catch (error) { 44 // error can be caused by lack of internet connection 45 alert alert('error!', error message); 46 return false; 47 } 48 }; 49	 50 const readtodos = async function () { 51 // reading parse objects is done by using parse query 52 const parsequery = new parse query('todo'); 53 try { 54 let todos = await parsequery find(); 55 // be aware that empty or invalid queries return as an empty array 56 // set results to state variable 57 setreadresults(todos); 58 return true; 59 } catch (error) { 60 // error can be caused by lack of internet connection 61 alert alert('error!', error message); 62 return false; 63 } 64 }; 65	 66 const updatetodo = async function (todoid, done) { 67 // create a new todo parse object instance and set todo id 68 let todo = new parse object('todo'); 69 todo set('objectid', todoid); 70 // set new done value and save parse object changes 71 todo set('done', done); 72 try { 73 await todo save(); 74 // success 75 alert alert('success!', 'todo updated!'); 76 // refresh todos list 77 readtodos(); 78 return true; 79 } catch (error) { 80 // error can be caused by lack of internet connection 81 alert alert('error!', error message); 82 return false; 83 }; 84 }; 85	 86 const deletetodo = async function (todoid) { 87 // create a new todo parse object instance and set todo id 88 let todo = new parse object('todo'); 89 todo set('objectid', todoid); 90 // destroy should be called to delete a parse object 91 try { 92 await todo destroy(); 93 alert alert('success!', 'todo deleted!'); 94 // refresh todos list to remove this one 95 readtodos(); 96 return true; 97 } catch (error) { 98 // error can be caused by lack of internet connection 99 alert alert('error!', error message); 100 return false; 101 } 102 }; 103	 104 return ( 105 <> 106 \<statusbar backgroundcolor="#208aec" /> 107 \<safeareaview style={styles container}> 108 \<view style={styles header}> 109 \<image 110 style={styles header logo} 111 source={ { 112 uri 113 'https //blog back4app com/wp content/uploads/2019/05/back4app white logo 500px png', 114 } } 115 /> 116 \<papertext style={styles header text bold}> 117 {'react native on back4app'} 118 \</papertext> 119 \<papertext style={styles header text}>{'product creation'}\</papertext> 120 \</view> 121 \<view style={styles wrapper}> 122 \<view style={styles flex between}> 123 \<title>todo list\</title> 124 {/ todo read (refresh) button /} 125 \<iconbutton 126 icon="refresh" 127 color={'#208aec'} 128 size={24} 129 onpress={() => readtodos()} 130 /> 131 \</view> 132 \<view style={styles create todo container}> 133 {/ todo create text input /} 134 \<papertextinput 135 value={newtodotitle} 136 onchangetext={text => setnewtodotitle(text)} 137 label="new todo" 138 mode="outlined" 139 style={styles create todo input} 140 /> 141 {/ todo create button /} 142 \<paperbutton 143 onpress={() => createtodo()} 144 mode="contained" 145 icon="plus" 146 color={'#208aec'} 147 style={styles create todo button}> 148 {'add'} 149 \</paperbutton> 150 \</view> 151 \<scrollview> 152 {/ todo read results list /} 153 {readresults !== null && 154 readresults !== undefined && 155 readresults map((todo) => ( 156 \<list item 157 key={todo id} 158 title={todo get('title')} 159 titlestyle={ 160 todo get('done') === true 161 ? styles todo text done 162 styles todo text 163 } 164 style={styles todo item} 165 right={props => ( 166 <> 167 {/ todo update button /} 168 {todo get('done') !== true && ( 169 \<touchableopacity 170 onpress={() => updatetodo(todo id, true)}> 171 \<list icon 172 { props} 173 icon="check" 174 color={'#4caf50'} 175 /> 176 \</touchableopacity> 177 )} 178 {/ todo delete button /} 179 \<touchableopacity onpress={() => deletetodo(todo id)}> 180 \<list icon { props} icon="close" color={'#ef5350'} /> 181 \</touchableopacity> 182 \</> 183 )} 184 /> 185 ))} 186 \</scrollview> 187 \</view> 188 \</safeareaview> 189 \</> 190 ); 191 }; 192	 193 // these define the screen component styles 194 const styles = stylesheet create({ 195 container { 196 flex 1, 197 backgroundcolor '#fff', 198 }, 199 wrapper { 200 width '90%', 201 alignself 'center', 202 }, 203 header { 204 alignitems 'center', 205 paddingtop 10, 206 paddingbottom 20, 207 backgroundcolor '#208aec', 208 }, 209 header logo { 210 width 170, 211 height 40, 212 marginbottom 10, 213 resizemode 'contain', 214 }, 215 header text bold { 216 color '#fff', 217 fontsize 14, 218 fontweight 'bold', 219 }, 220 header text { 221 margintop 3, 222 color '#fff', 223 fontsize 14, 224 }, 225 flex between { 226 flexdirection 'row', 227 alignitems 'center', 228 justifycontent 'space between', 229 }, 230 create todo container { 231 flexdirection 'row', 232 }, 233 create todo input { 234 flex 1, 235 height 38, 236 marginbottom 16, 237 backgroundcolor '#fff', 238 fontsize 14, 239 }, 240 create todo button { 241 margintop 6, 242 marginleft 15, 243 height 40, 244 }, 245 todo item { 246 borderbottomwidth 1, 247 borderbottomcolor 'rgba(0, 0, 0, 0 12)', 248 }, 249 todo text { 250 fontsize 15, 251 }, 252 todo text done { 253 color 'rgba(0, 0, 0, 0 3)', 254 fontsize 15, 255 textdecorationline 'line through', 256 }, 257 }) todolist tsx 1 import react, {fc, reactelement, usestate} from 'react'; 2 import { 3 alert, 4 view, 5 safeareaview, 6 image, 7 scrollview, 8 statusbar, 9 stylesheet, 10 touchableopacity, 11 } from 'react native'; 12 import parse from 'parse/react native'; 13 import { 14 list, 15 title, 16 iconbutton, 17 text as papertext, 18 button as paperbutton, 19 textinput as papertextinput, 20 } from 'react native paper'; 21	 22 export const todolist fc<{}> = ({}) reactelement => { 23 // state variables 24 const \[readresults, setreadresults] = usestate<\[parse object]>(); 25 const \[newtodotitle, setnewtodotitle] = usestate(''); 26	 27 // functions used by the screen components 28 const createtodo = async function () promise\<boolean> { 29 // this value comes from a state variable 30 const newtodotitlevalue string = newtodotitle; 31 // creates a new todo parse object instance 32 let todo parse object = new parse object('todo'); 33 todo set('title', newtodotitlevalue); 34 todo set('done', false); 35 // after setting the todo values, save it on the server 36 try { 37 await todo save(); 38 // success 39 alert alert('success!', 'todo created!'); 40 // refresh todos list to show the new one (you will create this function later) 41 readtodos(); 42 return true; 43 } catch (error) { 44 // error can be caused by lack of internet connection 45 alert alert('error!', error message); 46 return false; 47 } 48 }; 49	 50 const readtodos = async function () promise\<boolean> { 51 // reading parse objects is done by using parse query 52 const parsequery parse query = new parse query('todo'); 53 try { 54 let todos parse object\[] = await parsequery find(); 55 // be aware that empty or invalid queries return as an empty array 56 // set results to state variable 57 setreadresults(todos); 58 return true; 59 } catch (error) { 60 // error can be caused by lack of internet connection 61 alert alert('error!', error message); 62 return false; 63 } 64 }; 65	 66 const updatetodo = async function ( 67 todoid string, 68 done boolean, 69 ) promise\<boolean> { 70 // create a new todo parse object instance and set todo id 71 let todo parse object = new parse object('todo'); 72 todo set('objectid', todoid); 73 // set new done value and save parse object changes 74 todo set('done', done); 75 try { 76 await todo save(); 77 // success 78 alert alert('success!', 'todo updated!'); 79 // refresh todos list 80 readtodos(); 81 return true; 82 } catch (error) { 83 // error can be caused by lack of internet connection 84 alert alert('error!', error message); 85 return false; 86 } 87 }; 88	 89 const deletetodo = async function (todoid string) promise\<boolean> { 90 // create a new todo parse object instance and set todo id 91 let todo parse object = new parse object('todo'); 92 todo set('objectid', todoid); 93 // destroy should be called to delete a parse object 94 try { 95 await todo destroy(); 96 alert alert('success!', 'todo deleted!'); 97 // refresh todos list to remove this one 98 readtodos(); 99 return true; 100 } catch (error) { 101 // error can be caused by lack of internet connection 102 alert alert('error!', error message); 103 return false; 104 } 105 }; 106	 107 return ( 108 <> 109 \<statusbar backgroundcolor="#208aec" /> 110 \<safeareaview style={styles container}> 111 \<view style={styles header}> 112 \<image 113 style={styles header logo} 114 source={ { 115 uri 116 'https //blog back4app com/wp content/uploads/2019/05/back4app white logo 500px png', 117 } } 118 /> 119 \<papertext style={styles header text bold}> 120 {'react native on back4app'} 121 \</papertext> 122 \<papertext style={styles header text}>{'product creation'}\</papertext> 123 \</view> 124 \<view style={styles wrapper}> 125 \<view style={styles flex between}> 126 \<title>todo list\</title> 127 {/ todo read (refresh) button /} 128 \<iconbutton 129 icon="refresh" 130 color={'#208aec'} 131 size={24} 132 onpress={() => readtodos()} 133 /> 134 \</view> 135 \<view style={styles create todo container}> 136 {/ todo create text input /} 137 \<papertextinput 138 value={newtodotitle} 139 onchangetext={text => setnewtodotitle(text)} 140 label="new todo" 141 mode="outlined" 142 style={styles create todo input} 143 /> 144 {/ todo create button /} 145 \<paperbutton 146 onpress={() => createtodo()} 147 mode="contained" 148 icon="plus" 149 color={'#208aec'} 150 style={styles create todo button}> 151 {'add'} 152 \</paperbutton> 153 \</view> 154 \<scrollview> 155 {/ todo read results list /} 156 {readresults !== null && 157 readresults !== undefined && 158 readresults map((todo parse object) => ( 159 \<list item 160 key={todo id} 161 title={todo get('title')} 162 titlestyle={ 163 todo get('done') === true 164 ? styles todo text done 165 styles todo text 166 } 167 style={styles todo item} 168 right={props => ( 169 <> 170 {/ todo update button /} 171 {todo get('done') !== true && ( 172 \<touchableopacity 173 onpress={() => updatetodo(todo id, true)}> 174 \<list icon 175 { props} 176 icon="check" 177 color={'#4caf50'} 178 /> 179 \</touchableopacity> 180 )} 181 {/ todo delete button /} 182 \<touchableopacity onpress={() => deletetodo(todo id)}> 183 \<list icon { props} icon="close" color={'#ef5350'} /> 184 \</touchableopacity> 185 \</> 186 )} 187 /> 188 ))} 189 \</scrollview> 190 \</view> 191 \</safeareaview> 192 \</> 193 ); 194 }; 195	 196 // these define the screen component styles 197 const styles = stylesheet create({ 198 container { 199 flex 1, 200 backgroundcolor '#fff', 201 }, 202 wrapper { 203 width '90%', 204 alignself 'center', 205 }, 206 header { 207 alignitems 'center', 208 paddingtop 10, 209 paddingbottom 20, 210 backgroundcolor '#208aec', 211 }, 212 header logo { 213 width 170, 214 height 40, 215 marginbottom 10, 216 resizemode 'contain', 217 }, 218 header text bold { 219 color '#fff', 220 fontsize 14, 221 fontweight 'bold', 222 }, 223 header text { 224 margintop 3, 225 color '#fff', 226 fontsize 14, 227 }, 228 flex between { 229 flexdirection 'row', 230 alignitems 'center', 231 justifycontent 'space between', 232 }, 233 create todo container { 234 flexdirection 'row', 235 }, 236 create todo input { 237 flex 1, 238 height 38, 239 marginbottom 16, 240 backgroundcolor '#fff', 241 fontsize 14, 242 }, 243 create todo button { 244 margintop 6, 245 marginleft 15, 246 height 40, 247 }, 248 todo item { 249 borderbottomwidth 1, 250 borderbottomcolor 'rgba(0, 0, 0, 0 12)', 251 }, 252 todo text { 253 fontsize 15, 254 }, 255 todo text done { 256 color 'rgba(0, 0, 0, 0 3)', 257 fontsize 15, 258 textdecorationline 'line through', jika komponen anda disetel dengan benar, anda seharusnya melihat sesuatu seperti ini setelah membangun dan menjalankan aplikasi silakan tambahkan beberapa tugas dengan mengetikkan judulnya di kotak input satu per satu dan menekan tombol tambah tambah perhatikan bahwa setelah setiap pembuatan yang berhasil, fungsi createtodo createtodo memicu fungsi readtodos readtodos yang menyegarkan daftar tugas anda secara otomatis anda sekarang seharusnya memiliki daftar tugas yang cukup besar seperti ini anda sekarang dapat menandai tugas anda sebagai selesai dengan mengklik tanda centang di sampingnya, yang menyebabkan nilai selesai selesai diperbarui menjadi benar dan mengubah status ikonnya di sebelah kiri satu satunya operasi data yang tersisa sekarang adalah operasi hapus, yang dapat dilakukan dengan menekan ikon tempat sampah di paling kanan objek daftar tugas anda setelah berhasil menghapus objek, anda seharusnya mendapatkan pesan peringatan seperti ini kesimpulan di akhir panduan ini, anda telah belajar bagaimana melakukan operasi data dasar (crud) di parse pada react native di panduan berikutnya, kami akan menunjukkan jenis data apa yang didukung di parse dan bagaimana cara menggunakannya