In the heart of Parse Core feature is the data objects management. Parse allows you to store and query its data straightforwardly using its SDKs or APIs (REST or GraphQL). All the data object features are built using the Parse.Object class, which fields may contain key-value pairs of several JSON-compatible data types. The primary data types that can be assigned to the object fields are the following:
Number: integer (42) or floating-point (42.5) numbers, as long as ‘.’ is the decimal separator;
boolean: true or false values;
string: a string that can be as long as 2147483647 characters. Be aware that values this huge will slow down data operations;
DateTime: DateTimeobjects stored in UTC format as default. If you need to use another timezone, conversion should be done manually;
array: an array containing data in any Parse compatible data.
object: a JSON object also containing any Parse data. When available in SDK, an include() call will bring details from the Object property.
When you choose to use the Array type, we recommend keeping array objects small as this can affect your data operations’ overall performance. Our recommendation is to use the Array type if it does not exceed 20 elements and does not grow over time. Instead of the Array type, you can use the Pointer and Relations types as an alternative.
In this guide, you will learn how to store data in each of the basic data types listed above. You will build a product registration component on React, which will show you how to format, convert and save data to your Parse Server in React.
Parse also offers the datatypes GeoPoint to use the power of geolocation resources, and the Parse-specific relational data using the types Pointer or Relation. You will see both covered in the next following guides.
If you want to test/use the screen layout provided by this guide, you should set up the Ant Design library.
Goal
To understand the Parse-compatible basic data types, and to store each data type on Parse from a React component.
1 - The Product Creation Component
Let’s first create the component structure. Let’s make it simple and create a form screen with one text input to each data type, one checkbox, and a submit button to save the object. These inputs will collect your Product field values: name (string), quantity (number), price (number), available (boolean), expiration date (DateTime), and categories(array). Also, you will save an additional object type field in your saving method as well, but this one won’t need an input field.
Create a separate component in a file called ProductCreation.js/ProductCreation.tsx including the following code, or add it to your main application file (App.js/App.tsx). You can use this layout with complete stylings using Ant Design and adding the CSS code to your App.css file or set up your own custom form.
ProductCreation.js
ProductCreation.tsx
1import React,{ useState,FC, ReactElement }from'react';2import'./App.css';3import{ Button, Checkbox, Input }from'antd';4import{ PlusOutlined }from'@ant-design/icons';5const Parse =require('parse/dist/parse.min.js');67exportconst ProductCreation:FC<{}>=(): ReactElement =>{8// State variables9const[productName, setProductName]=useState('');10const[productQuantity, setProductQuantity]=useState('');11const[productPrice, setProductPrice]=useState('');12const[productAvailable, setProductAvailable]=useState(false);13const[productExpirationDate, setProductExpirationDate]=useState('');14const[productCategories, setProductCategories]=useState('');1516constcreateProduct=asyncfunction():Promise<boolean>{17try{18// These values come from state variables19// Convert data values to corresponding data types20const productNameValue:string= productName;21const productQuantityValue:number=Number(productQuantity);22const productPriceValue:number=Number(productPrice);23const productAvailableValue:boolean= productAvailable;24const productExpirationDateValue: Date =newDate(productExpirationDate);25const productCategoriesValue:string[]= productCategories.split(',');2627// Creates a new Product parse object instance28let Product: Parse.Object =newParse.Object('Product');2930// Set data to parse object31 Product.set('name', productNameValue);32 Product.set('quantity', productQuantityValue);33 Product.set('price', productPriceValue);34 Product.set('available', productAvailableValue);35 Product.set('expirationDate', productExpirationDateValue);36 Product.set('categories', productCategoriesValue);37 Product.set('completeData',{38 name: productNameValue,39 quantity: productQuantityValue,40 price: productPriceValue,41 available: productAvailableValue,42 expirationDate: productExpirationDateValue,43 categories: productCategoriesValue,44});4546// After setting the values, save it on the server47try{48let savedProduct: Parse.Object =await Product.save();49// Success50alert(`Success! ${JSON.stringify(savedProduct)}`);51returntrue;52}catch(error){53// Error can be caused by lack of Internet connection54alert(`Error! ${error.message}`);55returnfalse;56}57}catch(error:any){58// Error can be caused by wrong type of values in fields59alert(`Error! ${error.message}`);60returnfalse;61}62};6364return(65<div>66<div className="header">67<img
68 className="header_logo"69 alt="Back4App Logo"70 src={71'https://blog.back4app.com/wp-content/uploads/2019/05/back4app-white-logo-500px.png'72}73/>74<p className="header_text_bold">{'React on Back4App'}</p>75<p className="header_text">{'Product Creation'}</p>76</div>77<div className="container">78{/* Product field inputs */}79<div className="flex_between">80<h2 className="list_heading">Available?</h2>81<Checkbox
82 onChange={(e)=>setProductAvailable(e.target.checked)}83></Checkbox>84</div>85<div className="form_wrapper">86<Input
87 className="form_input"88 value={productName}89 onChange={(event)=>setProductName(event.target.value)}90 placeholder="Name"91 size="large"92/>93<Input
94 className="form_input"95 value={productQuantity}96 onChange={(event)=>setProductQuantity(event.target.value)}97 placeholder="Quantity"98 size="large"99/>100<Input
101 className="form_input"102 value={productPrice}103 onChange={(event)=>setProductPrice(event.target.value)}104 placeholder="Price"105 size="large"106/>107<Input
108 className="form_input"109 value={productExpirationDate}110 onChange={(event)=>setProductExpirationDate(event.target.value)}111 placeholder="Expiration Date (mm/dd/yyyy)"112 size="large"113/>114<Input
115 className="form_input"116 value={productCategories}117 onChange={(event)=>setProductCategories(event.target.value)}118 placeholder="Categories (separated by comma)"119 size="large"120/>121{/* Add product button */}122<Button
123 type="primary"124 className="form_button"125 color={'#208AEC'}126 size={'large'}127 onClick={createProduct}128 icon={<PlusOutlined />}129>130CREATEPRODUCT131</Button>132</div>133</div>134</div>135);136};
After setting up this screen, your application should look like this:
Note that each Product attribute has its text input field, except for the boolean checkbox input, meaning that the data in them needs conversion to the corresponding data type before saving.
2 - Converting Input Data
Before saving your data to the Parse.object, you need to correctly format the number, DateTime, and array inputs. Let’s now create a saving function, which will retrieve data from your state variables and apply the suitable data conversion:
ProductCreation.js
ProductCreation.tsx
1constcreateProduct=asyncfunction():Promise<boolean>{2try{3// These values come from state variables4// Convert data values to corresponding data types5const productNameValue:string= productName;6const productQuantityValue:number=Number(productQuantity);7const productPriceValue:number=Number(productPrice);8const productAvailableValue:boolean= productAvailable;9const productExpirationDateValue: Date =newDate(productExpirationDate);10const productCategoriesValue:string[]= productCategories.split(',');11}catch(error:any){12// Error can be caused by wrong type of values in fields13alert(`Error! ${error.message}`);14returnfalse;15}16};
The number data conversion is done casting the value as a Number JavaScript object. DateTime is converted using the Date JavaScript object constructor; the array one is created by using the String.split method in JavaScript, creating an array containing each entry of the categories field separated by commas.
Note that your data is now contained inside a single object, which can be set in a new Parse.object instance to be saved to the server using the Parse.Object.set() method, which takes two arguments: the field name and the value to be set. Let’s also set a new field called completeData, which will be your object type field, assigning the same data object to it.
Go ahead and complete the createProduct function with the following:
ProductCreation.js
ProductCreation.tsx
1constcreateProduct=asyncfunction():Promise<boolean>{2try{3// These values come from state variables4// Convert data values to corresponding data types5const productNameValue:string= productName;6const productQuantityValue:number=Number(productQuantity);7const productPriceValue:number=Number(productPrice);8const productAvailableValue:boolean= productAvailable;9const productExpirationDateValue: Date =newDate(productExpirationDate);10const productCategoriesValue:string[]= productCategories.split(',');1112// Creates a new Product parse object instance13let Product: Parse.Object =newParse.Object('Product');1415// Set data to parse object16 Product.set('name', productNameValue);17 Product.set('quantity', productQuantityValue);18 Product.set('price', productPriceValue);19 Product.set('available', productAvailableValue);20 Product.set('expirationDate', productExpirationDateValue);21 Product.set('categories', productCategoriesValue);22 Product.set('completeData',{23 name: productNameValue,24 quantity: productQuantityValue,25 price: productPriceValue,26 available: productAvailableValue,27 expirationDate: productExpirationDateValue,28 categories: productCategoriesValue,29});3031// After setting the values, save it on the server32try{33let savedProduct: Parse.Object =await Product.save();34// Success35alert(`Success! ${JSON.stringify(savedProduct)}`);36returntrue;37}catch(error:any){38// Error can be caused by lack of Internet connection39alert(`Error! ${error.message}`);40returnfalse;41};42}catch(error:any){43// Error can be caused by wrong type of values in fields44alert(`Error! ${error.message}`);45returnfalse;46}47};
You can now test the component, inserting the createProduct function in it, and calling it inside your form submit button onClick property. After creating a product, you should see an alert containing its data like this:
To certify that your data was saved on the server using the correct data types, you can look at your Parse dashboard. Click on the Product data table and note that every column has its data type written at the header. Your class should look like this:
Conclusion
At the end of this guide, you learned how to save each of the basic data types available on Parse using a React component. In the next guide, you will learn about the relational data on Parse.