React Native
...
Data objects
Consultas Básicas
11 min
consulta en react native usando parse introducción en esta guía, realizarás consultas básicas en parse e implementarás un componente de react native utilizando estas consultas aprenderás cómo configurar y consultar datos realistas usando back4app y react native requisitos previos para completar este tutorial, necesitarás una aplicación de react native creada y conectada a back4app si deseas probar/utilizar el diseño de pantalla proporcionado por esta guía, deberías configurar el react native paper react native paper biblioteca objetivo consultar datos almacenados en back4app desde una aplicación de react native 1 entendiendo la clase parse query cualquier operación de consulta de parse utiliza el parse query parse query tipo de objeto, que te ayudará a recuperar datos específicos de tu base de datos a lo largo de tu aplicación es crucial saber que un parse query parse query solo se resolverá después de llamar a un método de recuperación (como parse query find parse query find o parse query get parse query get ), por lo que se puede configurar una consulta y encadenar varios modificadores antes de ser realmente llamada para crear un nuevo parse query parse query , necesitas pasar como parámetro la deseada parse object parse object subclase, que es la que contendrá los resultados de tu consulta un ejemplo de consulta se puede ver a continuación, en la que se está consultando una subclase ficticia de 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(); puedes leer más sobre la parse query parse query clase aquí en la documentación oficial https //parseplatform org/parse sdk js/api/master/parse query html 2 guarda algunos datos en back4app vamos a crear una profile profile clase, que será el objetivo de nuestras consultas en esta guía en la consola js de parse es posible ejecutar código javascript directamente, consultando y actualizando el contenido de la base de datos de tu aplicación utilizando los comandos del sdk de js ejecuta el código a continuación desde tu consola js e inserta los datos en back4app así es como se ve la consola js en tu panel adelante y crea la clase de usuario profile profile con el siguiente contenido de ejemplo 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 consultar los datos ahora que tienes una clase poblada, podemos realizar algunas consultas básicas en ella comencemos filtrando perfil perfil resultados por nombre, que es un campo de tipo cadena, buscando valores que contengan el nombre adam adam usando el parse query contains parse query contains método 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 }; ahora consultemos por el campo de tipo número friendcount friendcount utilizando otro método de consulta común, parse query greaterthan parse query greaterthan en este caso, queremos usuarios profiles profiles en los que el conteo de amigos sea mayor que 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 }; otros métodos de consulta recurrentes son parse query ascending parse query ascending y parse query descending parse query descending , responsables de ordenar tus consultas este orden puede hacerse en la mayoría de los tipos de datos, así que ordenemos una consulta por el campo de fecha birthday birthday por el más joven 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 }; como se mencionó aquí antes, puedes y debes encadenar métodos de consulta para lograr resultados más refinados entonces, combinemos los ejemplos anteriores en una sola solicitud de consulta 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 consulta desde un componente de react native ahora usemos nuestras consultas de ejemplo dentro de un componente en react native, con una interfaz simple que tiene una lista que muestra resultados y también 4 botones para llamar a las consultas así es como se organiza el código del componente, note las doquery doquery funciones, que contienen el código de ejemplo de antes 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 }); así es como debería verse el componente después de renderizar y consultar mediante todas las funciones de consulta conclusión al final de esta guía, aprendiste cómo funcionan las consultas de datos básicas en parse y cómo realizarlas en back4app desde una aplicación de react native en la próxima guía, explorarás el parse query parse query potencial completo utilizando todos los métodos disponibles en esta clase