SlideShare a Scribd company logo
Lecture 11: Database in App:

AsyncStorage, Realm.

by Completing Selfies Scoreboard App
Kobkrit Viriyayudhakorn, Ph.D.
CEO of iApp Technology Limited.
kobkrit@gmail.com
http://www.kobkrit.com
Important Links
• Source Codes 

https://github.com/kobkrit/learn-react-native
• Course Materials

http://www.kobkrit.com/category/programming/react-
native/
• Score Announcement

http://bit.ly/its484quizscore
• Facebook Group

https://web.facebook.com/groups/ReactNativeThai/

Database on the App
• When you are develop the app, at one point, you
will need to store information permanently for an
application (it does not gone after the forced close
and re-open).
• For faster loading time, Line app use a local
database to remember all of your conversations.
• For caching propose, Facebook app use a local
database to record all of the previously loaded
news feed.
AsyncStorage
• AsyncStorage is a simple, unencrypted,
asynchronous, persistent, key-value storage
system that is global to the app.
• On iOS, AsyncStorage is backed by native code
that stores small values in a serialized dictionary
and larger values in separate files.
• On Android, AsyncStorage will use either RocksDB
or SQLite based on what is available.
How to use it?
• Don’t need to installation any extra library. It comes
with React-Native by default.



• AsyncStorage uses key-value pairs so to save
data, e.g. the following example.







1.js
How to use it?
• To loaded the saved data, you can do like this…





• Since loading data is a time consuming task, it is
designed to be a asynchronous operation. So
getItem returned the promise, which will invoke the
call back function when the read operation is
completed.
1.js
Simple Text Storage App
Kill the app, by pressing home button twice. Shift+Cmd+H
1.js
Create a new React-Native
Project
• $|> react-native init l11_storage
• Write down the code from 1.js into index.ios.js
• $|> react-native run-ios
Save data
Load data when

Initialize
1.js
What if.. the whole state is
save?
• For faster application development, Instead of we
manipulate the field one-by-one, we can save the
whole state into the AsyncStorage.
• setItem(), and getItem() accept only the string
arguments. How we can store the whole JSON
object?
• Use JSON.stringify() and JSON.parse() to
convert between string and JSON object.
2.js
JSON.stringify &
JSON.parse
• Object to String
• JSON.stringify({A:1, B:2}) => “{‘A’:1, ‘B’:2}”
• String to Object
• JSON.parse(“{‘A’:1, ‘B’:2}”) => {A:1, B:2}
2.js
Double Text Storage App
2.js
Saving / Loading the whole
state.
2.js
2.js
Removing the Storage
3.js
AsyncStorage in Selfies
Scoreboard App L10_CameraRollPicker/
selfiesWithAsyncStorage.js
Load information from 

the AsyncStorage
L10_CameraRollPicker/
selfiesWithAsyncStorage.js
L10_CameraRollPicker/
selfiesWithAsyncStorage.js
L10_CameraRollPicker/
selfiesWithAsyncStorage.js
But if we want more complex
database to use?
• AsyncStorage is just a key-value pair storage
• In practical application, we need to store complex
information much more than key-value pair.
• What if we want the database that can query,
search, and support encryption with data
modeling?
• is the answer!
Realm Database
• A flexible platform for creating offline-first, reactive
mobile apps effortlessly.
Realm Database
Realm Installation
• Change directories into the new project (cd
<project-name>) and add the realm dependency:
• $|> npm install --save realm
• Next use react-native to link your project to the
realm native module.
• $|> react-native link realm
Realm Database Basic
Refresh Refresh
realm1.js
Schema Definition
Create a new object
Show amount of object

saved in DB
Realm Database Model
• Realm data models are defined by the schema
information passed into a Realm during
initialization.
• The schema for an object consists of the object’s
name and a set of properties each of which has a
name and type as well as the objectType for object
and list properties.
• We can also designate each property to be
optional or to have a default value.
When specifying basic properties as a shorthand you may specify only the type
rather than having to specify a dictionary with a single entry:
Realm’s Basic Property Type
• Realm supports the following basic types: bool, int, float,
double, string, data, and date.
• bool properties map to JavaScript Boolean objects
• int, float, and double properties map to JavaScript Number
objects. Internally ‘int’ and ‘double’ are stored as 64 bits while
float is stored with 32 bits.
• string properties map to String
• data properties map to ArrayBuffer
• date properties map to Date
Object Properties
• To define the new object, we need to specify the name property of
the object schema we are referencing..
• When using object properties you need to make sure all referenced
types are present in the schema used to open the Realm
Accessing Object Properties
• When accessing object properties, you can access
nested properties using normal property syntax
List Properties
• For list properties you must specify the property
type as list as well as the objectType
Accessing List Property
• When accessing list properties a List object is
returned. List has methods very similar to a regular
JavaScript array. The big difference is that any
changes made to a List are automatically
persisted to the underlying Realm.
Optional Properties
• Properties can be declared as optional or non-
optional by specifying the optional designator in
your property definition:
Setting Optional Properties
Default Property
• Default property values can be specified by setting the
default designator in the property definition. To use a default
value, leave the property unspecified during object creation.
Index Property
• You can add an indexed designator to a property
definition to cause that property to be indexed. This
is supported for int, string, and bool property types:
• Indexing a property will greatly speed up queries
where the property is compared for equality at the
cost of slower insertions.
PrimaryKey Properties
• You can specify the primaryKey property in an object
model for string and int properties.
• Declaring a primary key allows objects to be looked up
and updated efficiently and enforces uniqueness for
each value.
• Once an object with a primary key has been added to
a Realm the primary key cannot be changed.
• Note that, Primary key properties are automatically
indexed.
PrimaryKey Properties
Writes: Creating Objects
• Objects are created by using the create method.
• Nested Objects can create recursively by specifying
JSON value of each child property.
Writes: Updating Objects
• You can update any object by setting its properties within a write
transaction.
• If the model class includes a primary key, you can have Realm
intelligently update or add objects based off of their primary key
values. This is done by passing true as the third argument to the
create method:
Writes: Deleting Objects
• Objects can be deleted by calling the delete
method within a write transaction.
Queries
• Queries allow you to get objects of a single type from a
Realm, with the option of filtering and sorting those
results.
• All queries (including queries and property access) are
lazy in Realm. Data is only read when objects and
properties are accessed. This allows you to represent
large sets of data in a performant way.
• When performing queries you are returned a Results
object. Results are simply a view of your data and are
not mutable.
Queries: Get All Objects
• The most basic method for retrieving objects from a
Realm is using the objects method on a Realm to
get all objects of a given type:
Filtering
• You can get a filtered Results by calling the filtered
method with a query string.
For example, the following would to retrieve all dogs with
the color tan and names beginning with ‘B’
Filtering Support Operations
• Basic comparison operators ==, !=, >, >=, <, and <= are
supported for numeric properties.
• ==, BEGINSWITH, ENDSWITH, and CONTAINS are
supported for string properties.
• String comparisons can be made case insensitive by
appending [c] to the operator: ==[c], BEGINSWITH[c] etc.
• Filtering by properties on linked or child objects can by
done by specifying a keypath in the query eg car.color ==
'blue'.
Sorting
• Results allows you to specify a sort criteria and
order based on a single or multiple properties.
• For example, the following call sorts the returned
cars from the example above numerically by miles:
let reversedSortedHondas = hondas.sorted(‘miles’,true);
Auto-Updating Result
• Results instances are live, auto-updating views into the
underlying data, which means results never have to be re-
fetched. Modifying objects that affect the query will be
reflected in the results immediately.
• This applies to all Results instances, included those
returned by the objects, filtered, and sorted methods.
Size Limiting
• Realm are lazy, performing this paginating behavior isn’t
necessary at all, as Realm will only load objects from the
results of the query once they are explicitly accessed.
• If for UI-related or other implementation reasons you
require a specific subset of objects from a query, it’s as
simple as taking the Results object, and reading out only
the objects you need.
Realm API Doc
• Realm API Reference
• https://realm.io/docs/react-native/latest/api/
• Realm Tutorial
• https://realm.io/docs/react-native/latest/#getting-
started

More Related Content

Similar to React-Native Lecture 11: In App Storage

Apex code (Salesforce)
Apex code (Salesforce)Apex code (Salesforce)
Apex code (Salesforce)
Mohammed Safwat Abu Kwaik
 
Bn1038 demo pega
Bn1038 demo  pegaBn1038 demo  pega
Bn1038 demo pega
conline training
 
C++ training
C++ training C++ training
C++ training
PL Sharma
 
Webinar: What's new in the .NET Driver
Webinar: What's new in the .NET DriverWebinar: What's new in the .NET Driver
Webinar: What's new in the .NET Driver
MongoDB
 
KnockoutJS and MVVM
KnockoutJS and MVVMKnockoutJS and MVVM
KnockoutJS and MVVM
Manvendra Singh
 
5variables in c#
5variables in c#5variables in c#
5variables in c#
Sireesh K
 
Android webinar class_5
Android webinar class_5Android webinar class_5
Android webinar class_5Edureka!
 
static MEMBER IN OOPS PROGRAMING LANGUAGE.pptx
static MEMBER IN OOPS PROGRAMING LANGUAGE.pptxstatic MEMBER IN OOPS PROGRAMING LANGUAGE.pptx
static MEMBER IN OOPS PROGRAMING LANGUAGE.pptx
urvashipundir04
 
static members in object oriented program.pptx
static members in object oriented program.pptxstatic members in object oriented program.pptx
static members in object oriented program.pptx
urvashipundir04
 
java framwork for HIBERNATE FRAMEWORK.pptx
java framwork for HIBERNATE FRAMEWORK.pptxjava framwork for HIBERNATE FRAMEWORK.pptx
java framwork for HIBERNATE FRAMEWORK.pptx
ramanujsaini2001
 
While writing program in any language, you need to use various variables to s...
While writing program in any language, you need to use various variables to s...While writing program in any language, you need to use various variables to s...
While writing program in any language, you need to use various variables to s...
bhargavi804095
 
11-Classes.ppt
11-Classes.ppt11-Classes.ppt
11-Classes.ppt
basavaraj852759
 
Webinar: What's new in the .NET Driver
Webinar: What's new in the .NET DriverWebinar: What's new in the .NET Driver
Webinar: What's new in the .NET Driver
MongoDB
 
Owner - Java properties reinvented.
Owner - Java properties reinvented.Owner - Java properties reinvented.
Owner - Java properties reinvented.
Luigi Viggiano
 
Java beans
Java beansJava beans
Java beans
Rajkiran Mummadi
 
Data-Analytics using python (Module 4).pptx
Data-Analytics using python (Module 4).pptxData-Analytics using python (Module 4).pptx
Data-Analytics using python (Module 4).pptx
DRSHk10
 
Streamlining JSON mapping
Streamlining JSON mappingStreamlining JSON mapping
Streamlining JSON mapping
Jonathan Lehr
 
JSON
JSONJSON
JSON
Yoga Raja
 

Similar to React-Native Lecture 11: In App Storage (20)

Apex code (Salesforce)
Apex code (Salesforce)Apex code (Salesforce)
Apex code (Salesforce)
 
Bn1038 demo pega
Bn1038 demo  pegaBn1038 demo  pega
Bn1038 demo pega
 
C++ training
C++ training C++ training
C++ training
 
About Python
About PythonAbout Python
About Python
 
Webinar: What's new in the .NET Driver
Webinar: What's new in the .NET DriverWebinar: What's new in the .NET Driver
Webinar: What's new in the .NET Driver
 
KnockoutJS and MVVM
KnockoutJS and MVVMKnockoutJS and MVVM
KnockoutJS and MVVM
 
5variables in c#
5variables in c#5variables in c#
5variables in c#
 
Android webinar class_5
Android webinar class_5Android webinar class_5
Android webinar class_5
 
static MEMBER IN OOPS PROGRAMING LANGUAGE.pptx
static MEMBER IN OOPS PROGRAMING LANGUAGE.pptxstatic MEMBER IN OOPS PROGRAMING LANGUAGE.pptx
static MEMBER IN OOPS PROGRAMING LANGUAGE.pptx
 
static members in object oriented program.pptx
static members in object oriented program.pptxstatic members in object oriented program.pptx
static members in object oriented program.pptx
 
Real World MVC
Real World MVCReal World MVC
Real World MVC
 
java framwork for HIBERNATE FRAMEWORK.pptx
java framwork for HIBERNATE FRAMEWORK.pptxjava framwork for HIBERNATE FRAMEWORK.pptx
java framwork for HIBERNATE FRAMEWORK.pptx
 
While writing program in any language, you need to use various variables to s...
While writing program in any language, you need to use various variables to s...While writing program in any language, you need to use various variables to s...
While writing program in any language, you need to use various variables to s...
 
11-Classes.ppt
11-Classes.ppt11-Classes.ppt
11-Classes.ppt
 
Webinar: What's new in the .NET Driver
Webinar: What's new in the .NET DriverWebinar: What's new in the .NET Driver
Webinar: What's new in the .NET Driver
 
Owner - Java properties reinvented.
Owner - Java properties reinvented.Owner - Java properties reinvented.
Owner - Java properties reinvented.
 
Java beans
Java beansJava beans
Java beans
 
Data-Analytics using python (Module 4).pptx
Data-Analytics using python (Module 4).pptxData-Analytics using python (Module 4).pptx
Data-Analytics using python (Module 4).pptx
 
Streamlining JSON mapping
Streamlining JSON mappingStreamlining JSON mapping
Streamlining JSON mapping
 
JSON
JSONJSON
JSON
 

More from Kobkrit Viriyayudhakorn

Thai E-Voting System
Thai E-Voting System Thai E-Voting System
Thai E-Voting System
Kobkrit Viriyayudhakorn
 
Thai National ID Card OCR
Thai National ID Card OCRThai National ID Card OCR
Thai National ID Card OCR
Kobkrit Viriyayudhakorn
 
Chochae Robot - Thai voice communication extension pack for Service Robot
Chochae Robot - Thai voice communication extension pack for Service RobotChochae Robot - Thai voice communication extension pack for Service Robot
Chochae Robot - Thai voice communication extension pack for Service Robot
Kobkrit Viriyayudhakorn
 
ศักยภาพของ AI สู่โอกาสใหม่แห่งการแข่งขันและความสำเร็จ (Thai AI updates in yea...
ศักยภาพของ AI สู่โอกาสใหม่แห่งการแข่งขันและความสำเร็จ (Thai AI updates in yea...ศักยภาพของ AI สู่โอกาสใหม่แห่งการแข่งขันและความสำเร็จ (Thai AI updates in yea...
ศักยภาพของ AI สู่โอกาสใหม่แห่งการแข่งขันและความสำเร็จ (Thai AI updates in yea...
Kobkrit Viriyayudhakorn
 
Thai Text processing by Transfer Learning using Transformer (Bert)
Thai Text processing by Transfer Learning using Transformer (Bert)Thai Text processing by Transfer Learning using Transformer (Bert)
Thai Text processing by Transfer Learning using Transformer (Bert)
Kobkrit Viriyayudhakorn
 
How Emoticon Affects Chatbot Users
How Emoticon Affects Chatbot UsersHow Emoticon Affects Chatbot Users
How Emoticon Affects Chatbot Users
Kobkrit Viriyayudhakorn
 
หัวใจของปัญญาประดิษฐ์ (Gradient Descent ทำงานอย่างไร)
หัวใจของปัญญาประดิษฐ์ (Gradient Descent ทำงานอย่างไร)หัวใจของปัญญาประดิษฐ์ (Gradient Descent ทำงานอย่างไร)
หัวใจของปัญญาประดิษฐ์ (Gradient Descent ทำงานอย่างไร)
Kobkrit Viriyayudhakorn
 
Check Raka Chatbot Pitching Presentation
Check Raka Chatbot Pitching PresentationCheck Raka Chatbot Pitching Presentation
Check Raka Chatbot Pitching Presentation
Kobkrit Viriyayudhakorn
 
[Lecture 3] AI and Deep Learning: Logistic Regression (Coding)
[Lecture 3] AI and Deep Learning: Logistic Regression (Coding)[Lecture 3] AI and Deep Learning: Logistic Regression (Coding)
[Lecture 3] AI and Deep Learning: Logistic Regression (Coding)
Kobkrit Viriyayudhakorn
 
[Lecture 4] AI and Deep Learning: Neural Network (Theory)
[Lecture 4] AI and Deep Learning: Neural Network (Theory)[Lecture 4] AI and Deep Learning: Neural Network (Theory)
[Lecture 4] AI and Deep Learning: Neural Network (Theory)
Kobkrit Viriyayudhakorn
 
[Lecture 2] AI and Deep Learning: Logistic Regression (Theory)
[Lecture 2] AI and Deep Learning: Logistic Regression (Theory)[Lecture 2] AI and Deep Learning: Logistic Regression (Theory)
[Lecture 2] AI and Deep Learning: Logistic Regression (Theory)
Kobkrit Viriyayudhakorn
 
ITS488 Lecture 6: Music and Sound Effect & GVR Try out.
ITS488 Lecture 6: Music and Sound Effect & GVR Try out.ITS488 Lecture 6: Music and Sound Effect & GVR Try out.
ITS488 Lecture 6: Music and Sound Effect & GVR Try out.
Kobkrit Viriyayudhakorn
 
Lecture 12: React-Native Firebase Authentication
Lecture 12: React-Native Firebase AuthenticationLecture 12: React-Native Firebase Authentication
Lecture 12: React-Native Firebase Authentication
Kobkrit Viriyayudhakorn
 
Unity Google VR Cardboard Deployment on iOS and Android
Unity Google VR Cardboard Deployment on iOS and AndroidUnity Google VR Cardboard Deployment on iOS and Android
Unity Google VR Cardboard Deployment on iOS and Android
Kobkrit Viriyayudhakorn
 
ITS488 Lecture 4: Google VR Cardboard Game Development: Basket Ball Game #2
ITS488 Lecture 4: Google VR Cardboard Game Development: Basket Ball Game #2ITS488 Lecture 4: Google VR Cardboard Game Development: Basket Ball Game #2
ITS488 Lecture 4: Google VR Cardboard Game Development: Basket Ball Game #2
Kobkrit Viriyayudhakorn
 
Lecture 4: ITS488 Digital Content Creation with Unity - Game and VR Programming
Lecture 4: ITS488 Digital Content Creation with Unity - Game and VR Programming Lecture 4: ITS488 Digital Content Creation with Unity - Game and VR Programming
Lecture 4: ITS488 Digital Content Creation with Unity - Game and VR Programming
Kobkrit Viriyayudhakorn
 
Lecture 2: C# Programming for VR application in Unity
Lecture 2: C# Programming for VR application in UnityLecture 2: C# Programming for VR application in Unity
Lecture 2: C# Programming for VR application in Unity
Kobkrit Viriyayudhakorn
 
Lecture 1 Introduction to VR Programming
Lecture 1 Introduction to VR ProgrammingLecture 1 Introduction to VR Programming
Lecture 1 Introduction to VR Programming
Kobkrit Viriyayudhakorn
 
Thai Word Embedding with Tensorflow
Thai Word Embedding with Tensorflow Thai Word Embedding with Tensorflow
Thai Word Embedding with Tensorflow
Kobkrit Viriyayudhakorn
 
Lecture 3 - ES6 Script Advanced for React-Native
Lecture 3 - ES6 Script Advanced for React-NativeLecture 3 - ES6 Script Advanced for React-Native
Lecture 3 - ES6 Script Advanced for React-Native
Kobkrit Viriyayudhakorn
 

More from Kobkrit Viriyayudhakorn (20)

Thai E-Voting System
Thai E-Voting System Thai E-Voting System
Thai E-Voting System
 
Thai National ID Card OCR
Thai National ID Card OCRThai National ID Card OCR
Thai National ID Card OCR
 
Chochae Robot - Thai voice communication extension pack for Service Robot
Chochae Robot - Thai voice communication extension pack for Service RobotChochae Robot - Thai voice communication extension pack for Service Robot
Chochae Robot - Thai voice communication extension pack for Service Robot
 
ศักยภาพของ AI สู่โอกาสใหม่แห่งการแข่งขันและความสำเร็จ (Thai AI updates in yea...
ศักยภาพของ AI สู่โอกาสใหม่แห่งการแข่งขันและความสำเร็จ (Thai AI updates in yea...ศักยภาพของ AI สู่โอกาสใหม่แห่งการแข่งขันและความสำเร็จ (Thai AI updates in yea...
ศักยภาพของ AI สู่โอกาสใหม่แห่งการแข่งขันและความสำเร็จ (Thai AI updates in yea...
 
Thai Text processing by Transfer Learning using Transformer (Bert)
Thai Text processing by Transfer Learning using Transformer (Bert)Thai Text processing by Transfer Learning using Transformer (Bert)
Thai Text processing by Transfer Learning using Transformer (Bert)
 
How Emoticon Affects Chatbot Users
How Emoticon Affects Chatbot UsersHow Emoticon Affects Chatbot Users
How Emoticon Affects Chatbot Users
 
หัวใจของปัญญาประดิษฐ์ (Gradient Descent ทำงานอย่างไร)
หัวใจของปัญญาประดิษฐ์ (Gradient Descent ทำงานอย่างไร)หัวใจของปัญญาประดิษฐ์ (Gradient Descent ทำงานอย่างไร)
หัวใจของปัญญาประดิษฐ์ (Gradient Descent ทำงานอย่างไร)
 
Check Raka Chatbot Pitching Presentation
Check Raka Chatbot Pitching PresentationCheck Raka Chatbot Pitching Presentation
Check Raka Chatbot Pitching Presentation
 
[Lecture 3] AI and Deep Learning: Logistic Regression (Coding)
[Lecture 3] AI and Deep Learning: Logistic Regression (Coding)[Lecture 3] AI and Deep Learning: Logistic Regression (Coding)
[Lecture 3] AI and Deep Learning: Logistic Regression (Coding)
 
[Lecture 4] AI and Deep Learning: Neural Network (Theory)
[Lecture 4] AI and Deep Learning: Neural Network (Theory)[Lecture 4] AI and Deep Learning: Neural Network (Theory)
[Lecture 4] AI and Deep Learning: Neural Network (Theory)
 
[Lecture 2] AI and Deep Learning: Logistic Regression (Theory)
[Lecture 2] AI and Deep Learning: Logistic Regression (Theory)[Lecture 2] AI and Deep Learning: Logistic Regression (Theory)
[Lecture 2] AI and Deep Learning: Logistic Regression (Theory)
 
ITS488 Lecture 6: Music and Sound Effect & GVR Try out.
ITS488 Lecture 6: Music and Sound Effect & GVR Try out.ITS488 Lecture 6: Music and Sound Effect & GVR Try out.
ITS488 Lecture 6: Music and Sound Effect & GVR Try out.
 
Lecture 12: React-Native Firebase Authentication
Lecture 12: React-Native Firebase AuthenticationLecture 12: React-Native Firebase Authentication
Lecture 12: React-Native Firebase Authentication
 
Unity Google VR Cardboard Deployment on iOS and Android
Unity Google VR Cardboard Deployment on iOS and AndroidUnity Google VR Cardboard Deployment on iOS and Android
Unity Google VR Cardboard Deployment on iOS and Android
 
ITS488 Lecture 4: Google VR Cardboard Game Development: Basket Ball Game #2
ITS488 Lecture 4: Google VR Cardboard Game Development: Basket Ball Game #2ITS488 Lecture 4: Google VR Cardboard Game Development: Basket Ball Game #2
ITS488 Lecture 4: Google VR Cardboard Game Development: Basket Ball Game #2
 
Lecture 4: ITS488 Digital Content Creation with Unity - Game and VR Programming
Lecture 4: ITS488 Digital Content Creation with Unity - Game and VR Programming Lecture 4: ITS488 Digital Content Creation with Unity - Game and VR Programming
Lecture 4: ITS488 Digital Content Creation with Unity - Game and VR Programming
 
Lecture 2: C# Programming for VR application in Unity
Lecture 2: C# Programming for VR application in UnityLecture 2: C# Programming for VR application in Unity
Lecture 2: C# Programming for VR application in Unity
 
Lecture 1 Introduction to VR Programming
Lecture 1 Introduction to VR ProgrammingLecture 1 Introduction to VR Programming
Lecture 1 Introduction to VR Programming
 
Thai Word Embedding with Tensorflow
Thai Word Embedding with Tensorflow Thai Word Embedding with Tensorflow
Thai Word Embedding with Tensorflow
 
Lecture 3 - ES6 Script Advanced for React-Native
Lecture 3 - ES6 Script Advanced for React-NativeLecture 3 - ES6 Script Advanced for React-Native
Lecture 3 - ES6 Script Advanced for React-Native
 

Recently uploaded

Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Globus
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
Tendenci - The Open Source AMS (Association Management Software)
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
Juraj Vysvader
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
Ortus Solutions, Corp
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
vrstrong314
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
kalichargn70th171
 
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Jay Das
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
abdulrafaychaudhry
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
Globus
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
Donna Lenk
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
Google
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
Max Andersen
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Natan Silnitsky
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
Matt Welsh
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
NYGGS Automation Suite
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
Globus
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
takuyayamamoto1800
 

Recently uploaded (20)

Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
Exploring Innovations in Data Repository Solutions - Insights from the U.S. G...
 
Corporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMSCorporate Management | Session 3 of 3 | Tendenci AMS
Corporate Management | Session 3 of 3 | Tendenci AMS
 
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
In 2015, I used to write extensions for Joomla, WordPress, phpBB3, etc and I ...
 
BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024BoxLang: Review our Visionary Licenses of 2024
BoxLang: Review our Visionary Licenses of 2024
 
top nidhi software solution freedownload
top nidhi software solution freedownloadtop nidhi software solution freedownload
top nidhi software solution freedownload
 
A Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdfA Comprehensive Look at Generative AI in Retail App Testing.pdf
A Comprehensive Look at Generative AI in Retail App Testing.pdf
 
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdfEnhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
Enhancing Project Management Efficiency_ Leveraging AI Tools like ChatGPT.pdf
 
Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024Globus Connect Server Deep Dive - GlobusWorld 2024
Globus Connect Server Deep Dive - GlobusWorld 2024
 
Lecture 1 Introduction to games development
Lecture 1 Introduction to games developmentLecture 1 Introduction to games development
Lecture 1 Introduction to games development
 
Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024Globus Compute Introduction - GlobusWorld 2024
Globus Compute Introduction - GlobusWorld 2024
 
Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"Navigating the Metaverse: A Journey into Virtual Evolution"
Navigating the Metaverse: A Journey into Virtual Evolution"
 
SOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBrokerSOCRadar Research Team: Latest Activities of IntelBroker
SOCRadar Research Team: Latest Activities of IntelBroker
 
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing SuiteAI Pilot Review: The World’s First Virtual Assistant Marketing Suite
AI Pilot Review: The World’s First Virtual Assistant Marketing Suite
 
Quarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden ExtensionsQuarkus Hidden and Forbidden Extensions
Quarkus Hidden and Forbidden Extensions
 
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.ILBeyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
Beyond Event Sourcing - Embracing CRUD for Wix Platform - Java.IL
 
Large Language Models and the End of Programming
Large Language Models and the End of ProgrammingLarge Language Models and the End of Programming
Large Language Models and the End of Programming
 
Prosigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology SolutionsProsigns: Transforming Business with Tailored Technology Solutions
Prosigns: Transforming Business with Tailored Technology Solutions
 
Enterprise Resource Planning System in Telangana
Enterprise Resource Planning System in TelanganaEnterprise Resource Planning System in Telangana
Enterprise Resource Planning System in Telangana
 
How to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good PracticesHow to Position Your Globus Data Portal for Success Ten Good Practices
How to Position Your Globus Data Portal for Success Ten Good Practices
 
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoamOpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
OpenFOAM solver for Helmholtz equation, helmholtzFoam / helmholtzBubbleFoam
 

React-Native Lecture 11: In App Storage

  • 1. Lecture 11: Database in App:
 AsyncStorage, Realm.
 by Completing Selfies Scoreboard App Kobkrit Viriyayudhakorn, Ph.D. CEO of iApp Technology Limited. kobkrit@gmail.com http://www.kobkrit.com
  • 2. Important Links • Source Codes 
 https://github.com/kobkrit/learn-react-native • Course Materials
 http://www.kobkrit.com/category/programming/react- native/ • Score Announcement
 http://bit.ly/its484quizscore • Facebook Group
 https://web.facebook.com/groups/ReactNativeThai/

  • 3. Database on the App • When you are develop the app, at one point, you will need to store information permanently for an application (it does not gone after the forced close and re-open). • For faster loading time, Line app use a local database to remember all of your conversations. • For caching propose, Facebook app use a local database to record all of the previously loaded news feed.
  • 4. AsyncStorage • AsyncStorage is a simple, unencrypted, asynchronous, persistent, key-value storage system that is global to the app. • On iOS, AsyncStorage is backed by native code that stores small values in a serialized dictionary and larger values in separate files. • On Android, AsyncStorage will use either RocksDB or SQLite based on what is available.
  • 5. How to use it? • Don’t need to installation any extra library. It comes with React-Native by default.
 
 • AsyncStorage uses key-value pairs so to save data, e.g. the following example.
 
 
 
 1.js
  • 6. How to use it? • To loaded the saved data, you can do like this…
 
 
 • Since loading data is a time consuming task, it is designed to be a asynchronous operation. So getItem returned the promise, which will invoke the call back function when the read operation is completed. 1.js
  • 7. Simple Text Storage App Kill the app, by pressing home button twice. Shift+Cmd+H 1.js
  • 8. Create a new React-Native Project • $|> react-native init l11_storage • Write down the code from 1.js into index.ios.js • $|> react-native run-ios
  • 9. Save data Load data when
 Initialize 1.js
  • 10. What if.. the whole state is save? • For faster application development, Instead of we manipulate the field one-by-one, we can save the whole state into the AsyncStorage. • setItem(), and getItem() accept only the string arguments. How we can store the whole JSON object? • Use JSON.stringify() and JSON.parse() to convert between string and JSON object. 2.js
  • 11. JSON.stringify & JSON.parse • Object to String • JSON.stringify({A:1, B:2}) => “{‘A’:1, ‘B’:2}” • String to Object • JSON.parse(“{‘A’:1, ‘B’:2}”) => {A:1, B:2} 2.js
  • 13. Saving / Loading the whole state. 2.js
  • 14. 2.js
  • 16. AsyncStorage in Selfies Scoreboard App L10_CameraRollPicker/ selfiesWithAsyncStorage.js
  • 17. Load information from 
 the AsyncStorage L10_CameraRollPicker/ selfiesWithAsyncStorage.js
  • 20. But if we want more complex database to use? • AsyncStorage is just a key-value pair storage • In practical application, we need to store complex information much more than key-value pair. • What if we want the database that can query, search, and support encryption with data modeling? • is the answer!
  • 21. Realm Database • A flexible platform for creating offline-first, reactive mobile apps effortlessly.
  • 23.
  • 24. Realm Installation • Change directories into the new project (cd <project-name>) and add the realm dependency: • $|> npm install --save realm • Next use react-native to link your project to the realm native module. • $|> react-native link realm
  • 26. realm1.js Schema Definition Create a new object Show amount of object
 saved in DB
  • 27. Realm Database Model • Realm data models are defined by the schema information passed into a Realm during initialization. • The schema for an object consists of the object’s name and a set of properties each of which has a name and type as well as the objectType for object and list properties. • We can also designate each property to be optional or to have a default value.
  • 28. When specifying basic properties as a shorthand you may specify only the type rather than having to specify a dictionary with a single entry:
  • 29. Realm’s Basic Property Type • Realm supports the following basic types: bool, int, float, double, string, data, and date. • bool properties map to JavaScript Boolean objects • int, float, and double properties map to JavaScript Number objects. Internally ‘int’ and ‘double’ are stored as 64 bits while float is stored with 32 bits. • string properties map to String • data properties map to ArrayBuffer • date properties map to Date
  • 30. Object Properties • To define the new object, we need to specify the name property of the object schema we are referencing.. • When using object properties you need to make sure all referenced types are present in the schema used to open the Realm
  • 31. Accessing Object Properties • When accessing object properties, you can access nested properties using normal property syntax
  • 32. List Properties • For list properties you must specify the property type as list as well as the objectType
  • 33. Accessing List Property • When accessing list properties a List object is returned. List has methods very similar to a regular JavaScript array. The big difference is that any changes made to a List are automatically persisted to the underlying Realm.
  • 34. Optional Properties • Properties can be declared as optional or non- optional by specifying the optional designator in your property definition:
  • 36. Default Property • Default property values can be specified by setting the default designator in the property definition. To use a default value, leave the property unspecified during object creation.
  • 37. Index Property • You can add an indexed designator to a property definition to cause that property to be indexed. This is supported for int, string, and bool property types: • Indexing a property will greatly speed up queries where the property is compared for equality at the cost of slower insertions.
  • 38. PrimaryKey Properties • You can specify the primaryKey property in an object model for string and int properties. • Declaring a primary key allows objects to be looked up and updated efficiently and enforces uniqueness for each value. • Once an object with a primary key has been added to a Realm the primary key cannot be changed. • Note that, Primary key properties are automatically indexed.
  • 40. Writes: Creating Objects • Objects are created by using the create method. • Nested Objects can create recursively by specifying JSON value of each child property.
  • 41. Writes: Updating Objects • You can update any object by setting its properties within a write transaction. • If the model class includes a primary key, you can have Realm intelligently update or add objects based off of their primary key values. This is done by passing true as the third argument to the create method:
  • 42. Writes: Deleting Objects • Objects can be deleted by calling the delete method within a write transaction.
  • 43. Queries • Queries allow you to get objects of a single type from a Realm, with the option of filtering and sorting those results. • All queries (including queries and property access) are lazy in Realm. Data is only read when objects and properties are accessed. This allows you to represent large sets of data in a performant way. • When performing queries you are returned a Results object. Results are simply a view of your data and are not mutable.
  • 44. Queries: Get All Objects • The most basic method for retrieving objects from a Realm is using the objects method on a Realm to get all objects of a given type:
  • 45. Filtering • You can get a filtered Results by calling the filtered method with a query string. For example, the following would to retrieve all dogs with the color tan and names beginning with ‘B’
  • 46. Filtering Support Operations • Basic comparison operators ==, !=, >, >=, <, and <= are supported for numeric properties. • ==, BEGINSWITH, ENDSWITH, and CONTAINS are supported for string properties. • String comparisons can be made case insensitive by appending [c] to the operator: ==[c], BEGINSWITH[c] etc. • Filtering by properties on linked or child objects can by done by specifying a keypath in the query eg car.color == 'blue'.
  • 47. Sorting • Results allows you to specify a sort criteria and order based on a single or multiple properties. • For example, the following call sorts the returned cars from the example above numerically by miles: let reversedSortedHondas = hondas.sorted(‘miles’,true);
  • 48. Auto-Updating Result • Results instances are live, auto-updating views into the underlying data, which means results never have to be re- fetched. Modifying objects that affect the query will be reflected in the results immediately. • This applies to all Results instances, included those returned by the objects, filtered, and sorted methods.
  • 49. Size Limiting • Realm are lazy, performing this paginating behavior isn’t necessary at all, as Realm will only load objects from the results of the query once they are explicitly accessed. • If for UI-related or other implementation reasons you require a specific subset of objects from a query, it’s as simple as taking the Results object, and reading out only the objects you need.
  • 50. Realm API Doc • Realm API Reference • https://realm.io/docs/react-native/latest/api/ • Realm Tutorial • https://realm.io/docs/react-native/latest/#getting- started