ReactJS
Data objects
Query di Base in React con Parse e Back4App
11 min
query in react utilizzando parse introduzione in questa guida, eseguirai query di base in parse e implementerai un componente react utilizzando queste query imparerai come configurare e interrogare dati realistici utilizzando back4app e react prerequisiti per completare questo tutorial, avrai bisogno di un'app react creata e collegata a back4app se desideri eseguire il progetto di esempio di questa guida, dovresti configurare la ant design ant design libreria obiettivo interrogare i dati memorizzati su back4app da un'applicazione react 1 comprendere la classe parse query qualsiasi operazione di query parse utilizza il tipo di oggetto parse query parse query che ti aiuterà a recuperare dati specifici dal tuo database in tutta l'app è fondamentale sapere che un parse query parse query si risolverà solo dopo aver chiamato un metodo di recupero (come parse query find parse query find o parse query get parse query get ), quindi una query può essere impostata e diversi modificatori possono essere concatenati prima di essere effettivamente chiamati per creare un nuovo parse query parse query , è necessario passare come parametro la parse object parse object sottoclasse desiderata, che sarà quella che conterrà i risultati della tua query un esempio di query può essere visto qui sotto, in cui viene interrogata una profile profile sottoclasse 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(); puoi leggere di più sulla parse query parse query classe qui nella documentazione ufficiale https //parseplatform org/parse sdk js/api/master/parse query html 2 salva alcuni dati su back4app creiamo una profile profile classe, che sarà l'obiettivo delle nostre query in questa guida sulla console js di parse è possibile eseguire codice javascript direttamente, interrogando e aggiornando i contenuti del database della tua applicazione utilizzando i comandi del js sdk esegui il codice qui sotto dalla tua console js e inserisci i dati su back4app ecco come appare la console js nel tuo dashboard procedi e crea la classe utente profilo profilo con il seguente contenuto di esempio 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 interrogare i dati ora che hai una classe popolata, possiamo eseguire alcune query di base in essa iniziamo filtrando profilo profilo i risultati per nome, che è un campo di tipo stringa, cercando valori che contengono il nome adam adam utilizzando il parse query contains parse query contains metodo 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 }; ora interroghiamo il campo di tipo numero friendcount friendcount utilizzando un altro metodo di query comune, parse query greaterthan parse query greaterthan in questo caso, vogliamo utenti profili profili in cui il conteggio degli amici è maggiore di 20 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 }; altri metodi di query ricorrenti sono parse query ascending parse query ascending e parse query descending parse query descending , responsabili dell'ordinamento delle tue query questo ordinamento può essere effettuato nella maggior parte dei tipi di dati, quindi ordiniamo una query per il campo data birthday birthday per il più giovane 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 }; come affermato qui prima, puoi e dovresti concatenare i metodi di query per ottenere risultati più raffinati combiniamo quindi i precedenti esempi in una singola richiesta di query 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 query da un componente react utilizziamo ora le nostre query di esempio all'interno di un componente in react, con un'interfaccia semplice che mostra un elenco di risultati e anche 4 pulsanti per chiamare le query questo è come è strutturato il codice del componente, nota le doquery doquery funzioni, contenenti il codice di esempio di prima javascript 1 import react, { usestate } from 'react'; 2 import parse from 'parse/dist/parse min js'; 3 import ' /app css'; 4 import { button, divider } from 'antd'; 5 import { closeoutlined, searchoutlined } from '@ant design/icons'; 6	 7 export const querybasic = () => { 8 // state variable 9 const \[queryresults, setqueryresults] = usestate(); 10	 11 const doquerybyname = async function () { 12 // create our parse query instance so methods can be chained 13 // reading parse objects is done by using parse query 14 const parsequery = new parse query('profile'); 15	 16 // `contains` is a basic query method that checks if string field 17 // contains a specific substring 18 parsequery contains('name', 'adam'); 19	 20 try { 21 let profiles = await parsequery find(); 22 setqueryresults(profiles); 23 return true; 24 } catch (error) { 25 // error can be caused by lack of internet connection 26 alert(`error! ${error message}`); 27 return false; 28 } 29 }; 30	 31 const doquerybyfriendcount = async function () { 32 // create our parse query instance so methods can be chained 33 // reading parse objects is done by using parse query 34 const parsequery = new parse query('profile'); 35	 36 // `greaterthan` is a basic query method that does what it 37 // says on the tin 38 parsequery greaterthan('friendcount', 20); 39	 40 try { 41 let profiles = await parsequery find(); 42 setqueryresults(profiles); 43 return true; 44 } catch (error) { 45 // error can be caused by lack of internet connection 46 alert(`error! ${error message}`); 47 return false; 48 } 49 }; 50	 51 const doquerybyordering = async function () { 52 // create our parse query instance so methods can be chained 53 // reading parse objects is done by using parse query 54 const parsequery = new parse query('profile'); 55	 56 // `descending` and `ascending` can and should be chained 57 // with other query methods to improve your queries 58 parsequery descending('birthday'); 59	 60 try { 61 let profiles = await parsequery find(); 62 setqueryresults(profiles); 63 return true; 64 } catch (error) { 65 // error can be caused by lack of internet connection 66 alert(`error! ${error message}`); 67 return false; 68 } 69 }; 70	 71 const doquerybyall = async function () { 72 // create our parse query instance so methods can be chained 73 // reading parse objects is done by using parse query 74 const parsequery = new parse query('profile'); 75	 76 parsequery contains('name', 'adam'); 77 parsequery greaterthan('friendcount', 20); 78 parsequery descending('birthday'); 79	 80 try { 81 let profiles = await parsequery find(); 82 setqueryresults(profiles); 83 return true; 84 } catch (error) { 85 // error can be caused by lack of internet connection 86 alert(`error! ${error message}`); 87 return false; 88 } 89 }; 90	 91 const clearqueryresults = async function () { 92 setqueryresults(undefined); 93 return true; 94 }; 95	 96 return ( 97 \<div> 98 \<div classname="header"> 99 \<img 100 classname="header logo" 101 alt="back4app logo" 102 src={ 103 'https //blog back4app com/wp content/uploads/2019/05/back4app white logo 500px png' 104 } 105 /> 106 \<p classname="header text bold">{'react on back4app'}\</p> 107 \<p classname="header text">{'basic queries'}\</p> 108 \</div> 109 \<div classname="container"> 110 \<div classname="flex between"> 111 \<h2 classname="heading">{'query list'}\</h2> 112 \<div classname="flex"> 113 \<button 114 onclick={() => doquerybyname()} 115 type="primary" 116 classname="heading button" 117 color={'#208aec'} 118 icon={\<searchoutlined />} 119 > 120 by name 121 \</button> 122 \<button 123 onclick={() => doquerybyfriendcount()} 124 type="primary" 125 classname="heading button" 126 color={'#208aec'} 127 icon={\<searchoutlined />} 128 > 129 by friend count 130 \</button> 131 \<button 132 onclick={() => doquerybyordering()} 133 type="primary" 134 classname="heading button" 135 color={'#208aec'} 136 icon={\<searchoutlined />} 137 > 138 by ordering 139 \</button> 140 \<button 141 onclick={() => doquerybyall()} 142 type="primary" 143 classname="heading button" 144 color={'#208aec'} 145 icon={\<searchoutlined />} 146 > 147 by all 148 \</button> 149 \<button 150 onclick={() => clearqueryresults()} 151 type="primary" 152 classname="heading button" 153 color={'#208aec'} 154 icon={\<closeoutlined />} 155 > 156 clear 157 \</button> 158 \</div> 159 \</div> 160 \<divider /> 161 \<div classname="flex between"> 162 \<div classname="flex child"> 163 {/ query list /} 164 {queryresults !== undefined && 165 queryresults map((profile, index) => ( 166 \<div classname="list item" key={`${index}`}> 167 \<p classname="list item title">{`${profile get('name')}`}\</p> 168 \<p classname="list item description">{`friend count ${profile get( 169 'friendcount' 170 )}, birthday ${profile get('birthday')}`}\</p> 171 \</div> 172 ))} 173 {queryresults !== undefined && queryresults length <= 0 ? ( 174 \<p>{'no results here!'}\</p> 175 ) null} 176 \</div> 177 \</div> 178 \</div> 179 \</div> 180 ); 181 }; typescript 1 import react, { usestate, fc, reactelement } from 'react'; 2 import ' /app css'; 3 import { button, divider } from 'antd'; 4 import { closeoutlined, searchoutlined } from '@ant design/icons'; 5 const parse = require('parse/dist/parse min js'); 6	 7 export const querybasic fc<{}> = () reactelement => { 8 // state variable 9 const \[queryresults, setqueryresults] = usestate\<parse object\[]>(); 10	 11 const doquerybyname = async function () promise\<boolean> { 12 // create our parse query instance so methods can be chained 13 // reading parse objects is done by using parse query 14 const parsequery parse query = new parse query('profile'); 15	 16 // `contains` is a basic query method that checks if string field 17 // contains a specific substring 18 parsequery contains('name', 'adam'); 19	 20 try { 21 let profiles parse object\[] = await parsequery find(); 22 setqueryresults(profiles); 23 return true; 24 } catch (error any) { 25 // error can be caused by lack of internet connection 26 alert(`error! ${error message}`); 27 return false; 28 } 29 }; 30	 31 const doquerybyfriendcount = async function () promise\<boolean> { 32 // create our parse query instance so methods can be chained 33 // reading parse objects is done by using parse query 34 const parsequery parse query = new parse query('profile'); 35	 36 // `greaterthan` is a basic query method that does what it 37 // says on the tin 38 parsequery greaterthan('friendcount', 20); 39	 40 try { 41 let profiles parse object\[] = await parsequery find(); 42 setqueryresults(profiles); 43 return true; 44 } catch (error any) { 45 // error can be caused by lack of internet connection 46 alert(`error! ${error message}`); 47 return false; 48 } 49 }; 50	 51 const doquerybyordering = async function () promise\<boolean> { 52 // create our parse query instance so methods can be chained 53 // reading parse objects is done by using parse query 54 const parsequery parse query = new parse query('profile'); 55	 56 // `descending` and `ascending` can and should be chained 57 // with other query methods to improve your queries 58 parsequery descending('birthday'); 59	 60 try { 61 let profiles parse object\[] = await parsequery find(); 62 setqueryresults(profiles); 63 return true; 64 } catch (error any) { 65 // error can be caused by lack of internet connection 66 alert(`error! ${error message}`); 67 return false; 68 } 69 }; 70	 71 const doquerybyall = async function () promise\<boolean> { 72 // create our parse query instance so methods can be chained 73 // reading parse objects is done by using parse query 74 const parsequery parse query = new parse query('profile'); 75	 76 parsequery contains('name', 'adam'); 77 parsequery greaterthan('friendcount', 20); 78 parsequery descending('birthday'); 79	 80 try { 81 let profiles parse object\[] = await parsequery find(); 82 setqueryresults(profiles); 83 return true; 84 } catch (error any) { 85 // error can be caused by lack of internet connection 86 alert(`error! ${error message}`); 87 return false; 88 } 89 }; 90	 91 const clearqueryresults = async function () promise\<boolean> { 92 setqueryresults(undefined); 93 return true; 94 }; 95	 96 return ( 97 \<div> 98 \<div classname="header"> 99 \<img 100 classname="header logo" 101 alt="back4app logo" 102 src={ 103 'https //blog back4app com/wp content/uploads/2019/05/back4app white logo 500px png' 104 } 105 /> 106 \<p classname="header text bold">{'react on back4app'}\</p> 107 \<p classname="header text">{'basic queries'}\</p> 108 \</div> 109 \<div classname="container"> 110 \<div classname="flex between"> 111 \<h2 classname="heading">{'query list'}\</h2> 112 \<div classname="flex"> 113 \<button 114 onclick={() => doquerybyname()} 115 type="primary" 116 classname="heading button" 117 color={'#208aec'} 118 icon={\<searchoutlined />} 119 > 120 by name 121 \</button> 122 \<button 123 onclick={() => doquerybyfriendcount()} 124 type="primary" 125 classname="heading button" 126 color={'#208aec'} 127 icon={\<searchoutlined />} 128 > 129 by friend count 130 \</button> 131 \<button 132 onclick={() => doquerybyordering()} 133 type="primary" 134 classname="heading button" 135 color={'#208aec'} 136 icon={\<searchoutlined />} 137 > 138 by ordering 139 \</button> 140 \<button 141 onclick={() => doquerybyall()} 142 type="primary" 143 classname="heading button" 144 color={'#208aec'} 145 icon={\<searchoutlined />} 146 > 147 by all 148 \</button> 149 \<button 150 onclick={() => clearqueryresults()} 151 type="primary" 152 classname="heading button" 153 color={'#208aec'} 154 icon={\<closeoutlined />} 155 > 156 clear 157 \</button> 158 \</div> 159 \</div> 160 \<divider /> 161 \<div classname="flex between"> 162 \<div classname="flex child"> 163 {/ query list /} 164 {queryresults !== undefined && 165 queryresults map((profile parse object, index number) => ( 166 \<div classname="list item" key={`${index}`}> 167 \<p classname="list item title">{`${profile get('name')}`}\</p> 168 \<p classname="list item description">{`friend count ${profile get( 169 'friendcount' 170 )}, birthday ${profile get('birthday')}`}\</p> 171 \</div> 172 ))} 173 {queryresults !== undefined && 174 queryresults length <= 0 ? ( 175 \<p>{'no results here!'}\</p> 176 ) null} 177 \</div> 178 \</div> 179 \</div> 180 \</div> 181 ); 182 }; aggiungi anche queste classi al tuo app css app css file per rendere correttamente tutti gli elementi dell'interfaccia 1 html { 2 box sizing border box; 3 outline none; 4 overflow auto; 5 } 6 7 , 8 before, 9 after { 10 margin 0; 11 padding 0; 12 box sizing inherit; 13 } 14 15 h1, 16 h2, 17 h3, 18 h4, 19 h5, 20 h6 { 21 margin 0; 22 font weight bold; 23 } 24 25 p { 26 margin 0; 27 } 28 29 body { 30 margin 0; 31 background color #fff; 32 } 33 34 container { 35 width 100%; 36 max width 900px; 37 margin auto; 38 padding 20px 0; 39 text align left; 40 } 41 42 header { 43 align items center; 44 padding 25px 0; 45 background color #208aec; 46 } 47 48 header logo { 49 height 55px; 50 margin bottom 20px; 51 object fit contain; 52 } 53 54 header text bold { 55 margin bottom 3px; 56 color rgba(255, 255, 255, 0 9); 57 font size 16px; 58 font weight bold; 59 } 60 61 header text { 62 color rgba(255, 255, 255, 0 9); 63 font size 15px; 64 } 65 66 heading { 67 font size 22px; 68 } 69 70 flex { 71 display flex; 72 } 73 74 flex between { 75 display flex; 76 justify content space between; 77 } 78 79 flex child { 80 flex 0 0 45%; 81 } 82 83 heading button { 84 margin left 12px; 85 } 86 87 list item { 88 padding bottom 15px; 89 margin bottom 15px; 90 border bottom 1px solid rgba(0,0,0,0 06); 91 text align left; 92 } 93 94 list item title { 95 color rgba(0,0,0,0 87); 96 font size 17px; 97 } 98 99 list item description { 100 color rgba(0,0,0,0 5); 101 font size 15px; 102 } ecco come dovrebbe apparire il componente dopo il rendering e la query tramite tutte le funzioni di query conclusione alla fine di questa guida, hai imparato come funzionano le query di base sui dati in parse e come eseguirle su back4app da un'app react nella prossima guida, esplorerai il parse query parse query pieno potenziale utilizzando tutti i metodi disponibili in questa classe