React Native
...
Data objects
Basic Queries
10 分
parseを使用したreact nativeでのクエリ はじめに このガイドでは、parseで基本的なクエリを実行し、これらのクエリを使用してreact nativeコンポーネントを実装します。back4appとreact nativeを使用して、現実的なデータを設定し、クエリを実行する方法を学びます。 前提条件 このチュートリアルを完了するには、次のものが必要です: 作成され、 back4app に接続されたreact nativeアプリ このガイドで提供される画面レイアウトをテスト/使用したい場合は、 react native paper react native paper を設定する必要があります。 ライブラリ 目標 react nativeアプリからback4appに保存されたデータをクエリします。 1 parse queryクラスの理解 任意のparseクエリ操作は、 parse query parse query オブジェクトタイプを使用し、アプリ全体でデータベースから特定のデータを取得するのに役立ちます。 parse query parse query は、リトリーブメソッド(例えば、 parse query find parse query find または parse query get parse query get )を呼び出した後にのみ解決されるため、クエリを設定し、実際に呼び出される前にいくつかの修飾子をチェーンすることができます。 新しい parse query parse query を作成するには、クエリ結果を含むサブクラスである希望の parse object parse object をパラメータとして渡す必要があります。以下に示す例のクエリでは、架空の profile profile サブクラスがクエリされています。 1 // this will create your query 2 let parsequery = new parse query("profile"); 3 // the query will resolve only after calling this method 4 let queryresult = await parsequery find(); 公式ドキュメントで parse query parse query クラスについてもっと読むことができます。 こちらで公式ドキュメントを確認してください https //parseplatform org/parse sdk js/api/master/parse query html 。 2 back4appにデータを保存する このガイドでのクエリのターゲットとなる profile profile クラスを作成しましょう。parse jsコンソールでは、javascriptコードを直接実行し、js sdkコマンドを使用してアプリケーションデータベースの内容をクエリおよび更新することができます。以下のコードをjsコンソールから実行し、back4appにデータを挿入してください。 ダッシュボードのjsコンソールはこのように見えます 以下の例の内容でユーザー profile profile クラスを作成してください 1 // add profile objects and create table 2 // adam sandler 3 let profile = new parse object('profile'); 4 profile set('name', 'adam sandler'); 5 profile set('birthday', new date('09/09/1966')); 6 profile set('friendcount', 2); 7 profile set('favoritefoods', \['lobster', 'bread']); 8 await profile save(); 9	 10 // adam levine 11 profile = new parse object('profile'); 12 profile set('name', 'adam levine'); 13 profile set('birthday', new date('03/18/1979')); 14 profile set('friendcount', 52); 15 profile set('favoritefoods', \['cake', 'bread']); 16 await profile save(); 17	 18 // carson kressley 19 profile = new parse object('profile'); 20 profile set('name', 'carson kressley'); 21 profile set('birthday', new date('11/11/1969')); 22 profile set('friendcount', 12); 23 profile set('favoritefoods', \['fish', 'cookies']); 24 await profile save(); 25	 26 // dan aykroyd 27 profile = new parse object('profile'); 28 profile set('name', 'dan aykroyd'); 29 profile set('birthday', new date('07/01/1952')); 30 profile set('friendcount', 66); 31 profile set('favoritefoods', \['jam', 'peanut butter']); 32 await profile save(); 33	 34 // eddie murphy 35 profile = new parse object('profile'); 36 profile set('name', 'eddie murphy'); 37 profile set('birthday', new date('04/03/1961')); 38 profile set('friendcount', 49); 39 profile set('favoritefoods', \['lettuce', 'pepper']); 40 await profile save(); 41	 42 // fergie 43 profile = new parse object('profile'); 44 profile set('name', 'fergie'); 45 profile set('birthday', new date('03/27/1975')); 46 profile set('friendcount', 55); 47 profile set('favoritefoods', \['lobster', 'shrimp']); 48 await profile save(); 49	 50 console log('success!'); 3 データをクエリする クラスが populated したので、基本的なクエリを実行できます。まず、名前で結果をフィルタリングすることから始めましょう。これは文字列型のフィールドで、名前 profile profile を含む値を検索します。名前 アダム アダム を使用して、 parse query contains parse query contains メソッドを使用します 1 // create your query 2 let parsequery = new parse query('profile'); 3	 4 // `contains` is a basic query method that checks if string field 5 // contains a specific substring 6 parsequery contains('name', 'adam'); 7	 8 // the query will resolve only after calling this method, retrieving 9 // an array of `parse objects` 10 let queryresults = await parsequery find(); 11	 12 // let's show the results 13 for (let result of queryresults) { 14 // you access `parse objects` attributes by using ` get` 15 console log(result get('name')); 16 }; では、数値型フィールド friendcount friendcount を別の一般的なクエリメソッド parse query greaterthan parse query greaterthan を使用してクエリしましょう。この場合、友達の数が20より大きいユーザー profiles profiles を取得したいと思います。 1 // create your query 2 let parsequery = new parse query('profile'); 3	 4 // `greaterthan` is a basic query method that does what it 5 // says on the tin 6 parsequery greaterthan('friendcount', 20); 7	 8 // the query will resolve only after calling this method, retrieving 9 // an array of `parse objects` 10 let queryresults = await parsequery find(); 11	 12 // let's show the results 13 for (let result of queryresults) { 14 // you access `parse objects` attributes by using ` get` 15 console log(`name ${result get('name')}, friend count ${result get('friendcount')}`); 16 }; 他の繰り返しクエリメソッドは parse query ascending parse query ascending と parse query descending parse query descending , クエリの順序を決定します。この順序付けはほとんどのデータ型で行うことができるので、日付フィールド birthday birthday を最も若い順に並べてみましょう。 1 // create your query 2 let parsequery = new parse query('profile'); 3	 4 // `descending` and `ascending` can and should be chained 5 // with other query methods to improve your queries 6 parsequery descending('birthday'); 7	 8 // the query will resolve only after calling this method, retrieving 9 // an array of `parse objects` 10 let queryresults = await parsequery find(); 11	 12 // let's show the results 13 for (let result of queryresults) { 14 // you access `parse objects` attributes by using ` get` 15 console log(`name ${result get('name')}, birthday ${result get('birthday')}`); 16 }; ここで以前に述べたように、クエリメソッドをチェーンして、より洗練された結果を得ることができます。それでは、前の例を単一のクエリリクエストに組み合わせてみましょう 1 // create your query 2 let parsequery = new parse query('profile'); 3	 4 parsequery contains('name', 'adam'); 5 parsequery greaterthan('friendcount', 20); 6 parsequery descending('birthday'); 7	 8 // the query will resolve only after calling this method, retrieving 9 // an array of `parse objects` 10 let queryresults = await parsequery find(); 11	 12 // let's show the results 13 for (let result of queryresults) { 14 // you access `parse objects` attributes by using ` get` 15 console log(`name ${result get('name')}, friend count ${result get('friendcount')}, birthday ${result get('birthday')}`); 16 }; 4 react nativeコンポーネントからのクエリ では、react nativeのコンポーネント内で例のクエリを使用し、結果を表示するリストとクエリを呼び出すための4つのボタンを持つシンプルなインターフェースを作成しましょう。コンポーネントコードのレイアウトは次のようになります。 doquery doquery 関数は、以前の例のコードを含んでいます。 javascript 1 import react, {usestate} from 'react'; 2 import {alert, image, view, scrollview, stylesheet} from 'react native'; 3 import parse from 'parse/react native'; 4 import { 5 list, 6 title, 7 button as paperbutton, 8 text as papertext, 9 } from 'react native paper'; 10	 11 export const booklist = () => { 12 // state variable 13 const \[queryresults, setqueryresults] = usestate(null); 14	 15 const doquerybyname = async function () { 16 // create our parse query instance so methods can be chained 17 // reading parse objects is done by using parse query 18 const parsequery = new parse query('profile'); 19	 20 // `contains` is a basic query method that checks if string field 21 // contains a specific substring 22 parsequery contains('name', 'adam'); 23	 24 try { 25 let profiles = await parsequery find(); 26 setqueryresults(profiles); 27 return true; 28 } catch (error) { 29 // error can be caused by lack of internet connection 30 alert alert('error!', error message); 31 return false; 32 } 33 }; 34	 35 const doquerybyfriendcount = async function () { 36 // create our parse query instance so methods can be chained 37 // reading parse objects is done by using parse query 38 const parsequery = new parse query('profile'); 39	 40 // `greaterthan` is a basic query method that does what it 41 // says on the tin 42 parsequery greaterthan('friendcount', 20); 43	 44 try { 45 let profiles = await parsequery find(); 46 setqueryresults(profiles); 47 return true; 48 } catch (error) { 49 // error can be caused by lack of internet connection 50 alert alert('error!', error message); 51 return false; 52 } 53 }; 54	 55 const doquerybyordering = async function () { 56 // create our parse query instance so methods can be chained 57 // reading parse objects is done by using parse query 58 const parsequery = new parse query('profile'); 59	 60 // `descending` and `ascending` can and should be chained 61 // with other query methods to improve your queries 62 parsequery descending('birthday'); 63	 64 try { 65 let profiles = await parsequery find(); 66 setqueryresults(profiles); 67 return true; 68 } catch (error) { 69 // error can be caused by lack of internet connection 70 alert alert('error!', error message); 71 return false; 72 } 73 }; 74	 75 const doquerybyall = async function () { 76 // create our parse query instance so methods can be chained 77 // reading parse objects is done by using parse query 78 const parsequery = new parse query('profile'); 79	 80 parsequery contains('name', 'adam'); 81 parsequery greaterthan('friendcount', 20); 82 parsequery descending('birthday'); 83	 84 try { 85 let profiles = await parsequery find(); 86 setqueryresults(profiles); 87 return true; 88 } catch (error) { 89 // error can be caused by lack of internet connection 90 alert alert('error!', error message); 91 return false; 92 } 93 }; 94	 95 const clearqueryresults = async function () { 96 setqueryresults(null); 97 return true; 98 }; 99	 100 return ( 101 <> 102 \<view style={styles header}> 103 \<image 104 style={styles header logo} 105 source={ { 106 uri 107 'https //blog back4app com/wp content/uploads/2019/05/back4app white logo 500px png', 108 } } 109 /> 110 \<papertext style={styles header text}> 111 \<papertext style={styles header text bold}> 112 {'react native on back4app '} 113 \</papertext> 114 {' basic queries'} 115 \</papertext> 116 \</view> 117 \<scrollview style={styles wrapper}> 118 \<view> 119 \<title>{'result list'}\</title> 120 {/ book list /} 121 {queryresults !== null && 122 queryresults !== undefined && 123 queryresults map((profile) => ( 124 \<list item 125 key={profile id} 126 title={profile get('name')} 127 description={`friend count ${profile get( 128 'friendcount', 129 )}, birthday ${profile get('birthday')}`} 130 titlestyle={styles list text} 131 style={styles list item} 132 /> 133 ))} 134 {queryresults === null || 135 queryresults === undefined || 136 (queryresults !== null && 137 queryresults !== undefined && 138 queryresults length <= 0) ? ( 139 \<papertext>{'no results here!'}\</papertext> 140 ) null} 141 \</view> 142 \<view> 143 \<title>{'query buttons'}\</title> 144 \<paperbutton 145 onpress={() => doquerybyname()} 146 mode="contained" 147 icon="search web" 148 color={'#208aec'} 149 style={styles list button}> 150 {'query by name'} 151 \</paperbutton> 152 \<paperbutton 153 onpress={() => doquerybyfriendcount()} 154 mode="contained" 155 icon="search web" 156 color={'#208aec'} 157 style={styles list button}> 158 {'query by friend count'} 159 \</paperbutton> 160 \<paperbutton 161 onpress={() => doquerybyordering()} 162 mode="contained" 163 icon="search web" 164 color={'#208aec'} 165 style={styles list button}> 166 {'query by ordering'} 167 \</paperbutton> 168 \<paperbutton 169 onpress={() => doquerybyall()} 170 mode="contained" 171 icon="search web" 172 color={'#208aec'} 173 style={styles list button}> 174 {'query by all'} 175 \</paperbutton> 176 \<paperbutton 177 onpress={() => clearqueryresults()} 178 mode="contained" 179 icon="delete" 180 color={'#208aec'} 181 style={styles list button}> 182 {'clear results'} 183 \</paperbutton> 184 \</view> 185 \</scrollview> 186 \</> 187 ); 188 }; 189	 190 // these define the screen component styles 191 const styles = stylesheet create({ 192 header { 193 alignitems 'center', 194 paddingtop 30, 195 paddingbottom 50, 196 backgroundcolor '#208aec', 197 }, 198 header logo { 199 height 50, 200 width 220, 201 resizemode 'contain', 202 }, 203 header text { 204 margintop 15, 205 color '#f0f0f0', 206 fontsize 16, 207 }, 208 header text bold { 209 color '#fff', 210 fontweight 'bold', 211 }, 212 wrapper { 213 width '90%', 214 alignself 'center', 215 }, 216 list button { 217 margintop 6, 218 marginleft 15, 219 height 40, 220 }, 221 list item { 222 borderbottomwidth 1, 223 borderbottomcolor 'rgba(0, 0, 0, 0 12)', 224 }, 225 list text { 226 fontsize 15, 227 }, 228 });1 import react, {fc, reactelement, usestate} from 'react'; 2 import {alert, image, view, scrollview, stylesheet} from 'react native'; 3 import parse from 'parse/react native'; 4 import { 5 list, 6 title, 7 button as paperbutton, 8 text as papertext, 9 } from 'react native paper'; 10	 11 export const querylist fc<{}> = ({}) reactelement => { 12 // state variable 13 const \[queryresults, setqueryresults] = usestate(null); 14	 15 const doquerybyname = async function () promise\<boolean> { 16 // create our parse query instance so methods can be chained 17 // reading parse objects is done by using parse query 18 const parsequery parse query = new parse query('profile'); 19	 20 // `contains` is a basic query method that checks if string field 21 // contains a specific substring 22 parsequery contains('name', 'adam'); 23	 24 try { 25 let profiles \[parse object] = await parsequery find(); 26 setqueryresults(profiles); 27 return true; 28 } catch (error) { 29 // error can be caused by lack of internet connection 30 alert alert('error!', error message); 31 return false; 32 } 33 }; 34	 35 const doquerybyfriendcount = async function () promise\<boolean> { 36 // create our parse query instance so methods can be chained 37 // reading parse objects is done by using parse query 38 const parsequery parse query = new parse query('profile'); 39	 40 // `greaterthan` is a basic query method that does what it 41 // says on the tin 42 parsequery greaterthan('friendcount', 20); 43	 44 try { 45 let profiles \[parse object] = await parsequery find(); 46 setqueryresults(profiles); 47 return true; 48 } catch (error) { 49 // error can be caused by lack of internet connection 50 alert alert('error!', error message); 51 return false; 52 } 53 }; 54	 55 const doquerybyordering = async function () promise\<boolean> { 56 // create our parse query instance so methods can be chained 57 // reading parse objects is done by using parse query 58 const parsequery parse query = new parse query('profile'); 59	 60 // `descending` and `ascending` can and should be chained 61 // with other query methods to improve your queries 62 parsequery descending('birthday'); 63	 64 try { 65 let profiles \[parse object] = await parsequery find(); 66 setqueryresults(profiles); 67 return true; 68 } catch (error) { 69 // error can be caused by lack of internet connection 70 alert alert('error!', error message); 71 return false; 72 } 73 }; 74	 75 const doquerybyall = async function () promise\<boolean> { 76 // create our parse query instance so methods can be chained 77 // reading parse objects is done by using parse query 78 const parsequery parse query = new parse query('profile'); 79	 80 parsequery contains('name', 'adam'); 81 parsequery greaterthan('friendcount', 20); 82 parsequery descending('birthday'); 83	 84 try { 85 let profiles \[parse object] = await parsequery find(); 86 setqueryresults(profiles); 87 return true; 88 } catch (error) { 89 // error can be caused by lack of internet connection 90 alert alert('error!', error message); 91 return false; 92 } 93 }; 94	 95 const clearqueryresults = async function () promise\<boolean> { 96 setqueryresults(null); 97 return true; 98 }; 99	 100 return ( 101 <> 102 \<view style={styles header}> 103 \<image 104 style={styles header logo} 105 source={ { 106 uri 107 'https //blog back4app com/wp content/uploads/2019/05/back4app white logo 500px png', 108 } } 109 /> 110 \<papertext style={styles header text}> 111 \<papertext style={styles header text bold}> 112 {'react native on back4app '} 113 \</papertext> 114 {' basic queries'} 115 \</papertext> 116 \</view> 117 \<scrollview style={styles wrapper}> 118 \<view> 119 \<title>{'result list'}\</title> 120 {/ book list /} 121 {queryresults !== null && 122 queryresults !== undefined && 123 queryresults map((profile parse object) => ( 124 \<list item 125 key={profile id} 126 title={profile get('name')} 127 description={`friend count ${profile get( 128 'friendcount', 129 )}, birthday ${profile get('birthday')}`} 130 titlestyle={styles list text} 131 style={styles list item} 132 /> 133 ))} 134 {queryresults === null || 135 queryresults === undefined || 136 (queryresults !== null && 137 queryresults !== undefined && 138 queryresults length <= 0) ? ( 139 \<papertext>{'no results here!'}\</papertext> 140 ) null} 141 \</view> 142 \<view> 143 \<title>{'query buttons'}\</title> 144 \<paperbutton 145 onpress={() => doquerybyname()} 146 mode="contained" 147 icon="search web" 148 color={'#208aec'} 149 style={styles list button}> 150 {'query by name'} 151 \</paperbutton> 152 \<paperbutton 153 onpress={() => doquerybyfriendcount()} 154 mode="contained" 155 icon="search web" 156 color={'#208aec'} 157 style={styles list button}> 158 {'query by friend count'} 159 \</paperbutton> 160 \<paperbutton 161 onpress={() => doquerybyordering()} 162 mode="contained" 163 icon="search web" 164 color={'#208aec'} 165 style={styles list button}> 166 {'query by ordering'} 167 \</paperbutton> 168 \<paperbutton 169 onpress={() => doquerybyall()} 170 mode="contained" 171 icon="search web" 172 color={'#208aec'} 173 style={styles list button}> 174 {'query by all'} 175 \</paperbutton> 176 \<paperbutton 177 onpress={() => clearqueryresults()} 178 mode="contained" 179 icon="delete" 180 color={'#208aec'} 181 style={styles list button}> 182 {'clear results'} 183 \</paperbutton> 184 \</view> 185 \</scrollview> 186 \</> 187 ); 188 }; 189	 190 // these define the screen component styles 191 const styles = stylesheet create({ 192 header { 193 alignitems 'center', 194 paddingtop 30, 195 paddingbottom 50, 196 backgroundcolor '#208aec', 197 }, 198 header logo { 199 height 50, 200 width 220, 201 resizemode 'contain', 202 }, 203 header text { 204 margintop 15, 205 color '#f0f0f0', 206 fontsize 16, 207 }, 208 header text bold { 209 color '#fff', 210 fontweight 'bold', 211 }, 212 wrapper { 213 width '90%', 214 alignself 'center', 215 }, 216 list button { 217 margintop 6, 218 marginleft 15, 219 height 40, 220 }, 221 list item { 222 borderbottomwidth 1, 223 borderbottomcolor 'rgba(0, 0, 0, 0 12)', 224 }, 225 list text { 226 fontsize 15, 227 }, 228 }); コンポーネントがレンダリングされ、すべてのクエリ関数によってクエリされた後の見た目は次のようになります 結論 このガイドの最後に、parseでの基本的なデータクエリの動作と、react nativeアプリからback4appでそれらを実行する方法を学びました。次のガイドでは、 parse query parse query クラスで利用可能なすべてのメソッドを使用して、その完全な可能性を探ります。