LateInitializationError - lifecyle of flutter - database

I am learning Flutter and right now testing an app to use SQLite. I wanted to use firebase in the long run, so I am building codes to store the token to the DB, but I think that I didn't quite get the process.
The LateInitializationError happens, but then it also does print the token so I guess I messed up the lifecycle?
So my question is,
why does the error happen and then print out the token?
how can I store the tokenValue data into the DB?
been 2 months and still not getting in the hang of flutter...
+Edit
This is the Error Message after putting an empty value
======== Exception caught by widgets library =======================================================
The following NoSuchMethodError was thrown building Builder:
Class 'Future<dynamic>' has no instance method 'insertToken'.
Receiver: Instance of 'Future<dynamic>'
Tried calling: insertToken(Instance of 'Token')
The relevant error-causing widget was:
MaterialApp file:///C:/Users/katej/Desktop/firem6_demo/lib/main.dart:17:5
When the exception was thrown, this was the stack:
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
#1 _MyAppState.initState (package:firem6_demo/main.dart:49:15)
#2 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4711:57)
#3 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4548:5)
... Normal element mounting (166 frames)
...
====================================================================================================
I/flutter ( 9579): (token)
I/flutter ( 9579): []
======== Exception caught by widgets library =======================================================
The following NoSuchMethodError was thrown building Builder:
Class 'Future<dynamic>' has no instance method 'insertToken'.
Receiver: Instance of 'Future<dynamic>'
Tried calling: insertToken(Instance of 'Token')
The relevant error-causing widget was:
MaterialApp file:///C:/Users/katej/Desktop/firem6_demo/lib/main.dart:17:5
When the exception was thrown, this was the stack:
#0 Object.noSuchMethod (dart:core-patch/object_patch.dart:54:5)
#1 _MyAppState.initState (package:firem6_demo/main.dart:49:15)
#2 StatefulElement._firstBuild (package:flutter/src/widgets/framework.dart:4711:57)
#3 ComponentElement.mount (package:flutter/src/widgets/framework.dart:4548:5)
... Normal element mounting (4 frames)
...
This is the main.dart
Future<void> main() async {
WidgetsFlutterBinding.ensureInitialized();
await Firebase.initializeApp();
runApp(
MaterialApp(home: MyApp()),
);
}
class MyApp extends StatefulWidget {
const MyApp({Key? key}) : super(key: key);
#override
_MyAppState createState() => _MyAppState();
}
class _MyAppState extends State<MyApp> {
late FirebaseMessaging messaging;
late String tokenValue;
void copyToken() {
(() {
if (tokenValue != null) {
Clipboard.setData(ClipboardData(text: tokenValue));}
}());
}
#override
void initState() {
messaging = FirebaseMessaging.instance;
messaging.getToken().then((value) {
tokenValue = value!;
copyToken();
print(tokenValue);
});
tokenDb();
var user1 = Token(token: tokenValue);
tokenDb().insertToken(user1);
tokenDb().updateToken(user1);
super.initState();
}
#override
Widget build(BuildContext context) {
return MaterialApp(
title: "DemoApp",
home: BottomBarScreen(),
routes: {
MonitoringScreen.routeName: (context) => MonitoringScreen(),
GuideScreen.routeName: (context) => GuideScreen(),
PracticeScreen.routeName: (context) => PracticeScreen(),
SettingsScreen.routeName: (context) => SettingsScreen()
},
);
}
}
And this is the db_test.dart which has tokenDb() function in it.
import 'dart:async';
import 'package:path/path.dart';
import 'package:sqflite/sqflite.dart';
tokenDb() async {
final database = openDatabase(
join(await getDatabasesPath(), 'token_list.db'),
onCreate: (db, version) {
return db.execute(
"CREATE TABLE tokens (token INTEGER PRIMARY KEY)",
);
},
version: 1,
);
Future<void> insertToken(Token token) async {
final Database db = await database;
await db.insert(
'tokens',
token.toMap(),
conflictAlgorithm: ConflictAlgorithm.replace,
);
}
Future<List<Token>> tokens() async {
final Database db = await database;
final List<Map<String, dynamic>> maps = await db.query('tokens');
return List.generate(maps.length, (i) {
return Token(
token: maps[i]['token']
);
});
}
Future<void> updateToken(Token token) async {
final db = await database;
await db.update(
'tokens',
token.toMap(),
where: "id = ?",
whereArgs: [token.token],
);
}
Future<void> deleteToken(int id) async {
final db = await database;
await db.delete(
'tokens',
where: "id = ?",
whereArgs: [id],
);
}
print(await tokens());
}
class Token {
String? token;
Token({this.token});
Map<String, dynamic> toMap() {
final map = Map<String, dynamic>();
map['token'] = token;
return map;
}
factory Token.fromMap(Map<String, dynamic> map) {
return Token(token: map['token']);
}
}
Inside the Main initState(), the tokenDb().insertToken(user1) does not work; the insertToken is not pointing to the function in the tokenDb.
thank you!

From
late String tokenValue;
To
String tokenValue = '';
Would resolve it.

Related

How do I create my second Data Table in This Database?

I have one data table named "visits" and its working fine. Now I am trying to create another data table name "bookings". But I can not do it. Is there any one who can help me to create the new data table? This my my DBHelper Class code:
DB Helper Class:
======================
import 'package:mrhandyman_admin/models/visit_list_model.dart';
import 'package:sqflite/sqflite.dart';
class DBHelper {
static Database? _db;
static final int _version = 1;
static final String _tableName="visits";
static Future<void> initDb() async {
if (_db != null) {
return;
}
try {
String _path = await getDatabasesPath() + 'visits.db';
_db = await openDatabase(
_path,
version: _version,
onCreate: (db, version) async {
print("Creating a new entry");
return await db.execute(
"CREATE TABLE $_tableName("
"id INTEGER PRIMARY KEY AUTOINCREMENT,"
"customerName STRING, customerPhone STRING,"
"moveFromAddress STRING, moveToAddress STRING,"
"visitDate STRING, visitTime STRING, remind INTEGER,"
"isCompleted INTEGER)",
);
},
);
} catch (e) {
print(e);
}
}
static Future<int> insert(VisitListModel? visitListModel) async {
print("insert function called");
return await _db?.insert(_tableName, visitListModel!.toJson())??1;
}
static Future<List<Map<String, dynamic>>> query() async {
print("query function called");
return await _db!.query(_tableName);
}
static delete(VisitListModel visitListModel) async {
return await _db!.delete(_tableName, where: 'id=?', whereArgs: [visitListModel.id]);
}
static update(int id) async{
return await _db!.rawUpdate('''
UPDATE visits
SET isCompleted = ?
WHERE id =?
''', [1, id]
);
}
}
Visit Controller
import 'package:get/get.dart';
import 'package:mrhandyman_admin/database/db_helper.dart';
import 'package:mrhandyman_admin/models/visit_list_model.dart';
class VisitListController extends GetxController{
#override
void onReady() {
super.onReady();
}
var visitList = <VisitListModel>[].obs;
Future<int> addVisit({VisitListModel? visitListModel}) async {
return await DBHelper.insert(visitListModel);
}
//get all data from table
void getVisits() async {
List<Map<String, dynamic>> visits = await DBHelper.query();
visitList.assignAll(visits.map((data) => new VisitListModel.fromJson(data)).toList());
}
void delete(VisitListModel visitListModel) async {
await DBHelper.delete(visitListModel);
getVisits();
}
void markTaskCompleted(int id) async {
await DBHelper.update(id);
getVisits();
}
}
Hello, I have one data table named "visits" and its working fine. Now I am trying to create another data table name "bookings". But I can not do it. Is there any one who can help me to create the new data table? This my my DBHelper Class code:

Flutter: Add Array to Firestore with a Button

I am working on developing an app and am currently in the account creation part. I want users to tap on buttons, and the text would be added to a Firestore database that I have created.
Currently, my problem is that I am not sure how to go about setting that up. I have repositories and blocs created for other components of the account creation, but I am struggling to figure out how to create buttons that will store the text as an array in Firestore. I have attached an image of what my screen will look like, my Firestore screen, as well as the code of my database repository and the chunk of code I have thus far with creating buttons that will store the text. The code for my button does NOT work, so I was hoping that I could get some help :):
Database Repository:
class DatabaseRepository extends BaseDatabaseRepository {
final FirebaseFirestore _firebaseFirestore = FirebaseFirestore.instance;
#override
Stream<User> getUser(String userId) {
return _firebaseFirestore
.collection('Users')
.doc(userId)
.snapshots()
.map((snap) => User.fromSnapshot(snap));
}
#override
Stream <List<User>> getUsers(
String userId
) {
return _firebaseFirestore
.collection('Users').snapshots().map((snap) {
return snap.docs.map((doc) => User.fromSnapshot(doc)).toList();
});
}
#override
Future<void> updateUserPictures(User user, String imageName) async{
String downloadURL = await StorageRepository().getDownloadURL(user, imageName);
return _firebaseFirestore
.collection('Users')
.doc(user.id)
.update({
'imageUrls': FieldValue.arrayUnion([downloadURL])});
}
#override
Future<void> UpdateUser(User user) async{
return _firebaseFirestore
.collection('Users')
.doc(user.id)
.update(user.toMap())
.then((value) =>
print('User document updated.'));
}
#override
Future<void> createUser(User user) async{
await _firebaseFirestore
.collection('Users')
.doc(user.id)
.set(user.toMap());
}
}
Button code (thus far):
Widget _button (event) => TextButton(
onPressed: () async {
DocumentReference documentReference = FirebaseFirestore.instance.collection('Users').doc();
DocumentSnapshot doc = await documentReference.get();
List Interests = doc.data('Interests');
if (Interests.contains(event == true) ) {}
},
child: Text(event,
style: GoogleFonts.montserrat()));

Not saving the flutter switch value to sqflite database

I am a completely a beginner to sqlite and flutter. I was trying to create a local database to my flutter to do app. So I watched some youtube videos and started to implementing a database using flutter sqflite plugin. Everything worked fine because all I did was copy typing the you tubers code, until I had to add an extra parameter to the code which is a boolean, in order to track the status of the task (like done the task or not). I used an int value to save the bool, while sqlite does not supports boolean values. I used two functions, one to update the text and the other to update the switch value.
And secondly when I tap on a switch it triggers all the switches in the list. I want to solve that issue as well.
Model class for the Task
class Tasksdb {
final int? id;
final String taskName;
bool isDone;
Tasksdb({
this.id,
required this.taskName,
required this.isDone,
});
factory Tasksdb.fromMap(Map<String, dynamic> json) => Tasksdb(
id: json['id'],
taskName: json['taskName'],
isDone: (json['isDone'] as int) == 0 ? false : true);
Map<String, dynamic> toMap() {
return {
'id': id,
'taskName': taskName,
'isDone': isDone,
};
}
}
DatabaseHelper class
class DatabaseHelper {
DatabaseHelper._privateConstructor();
static final DatabaseHelper instance = DatabaseHelper._privateConstructor();
static Database? _database;
Future<Database> get database async => _database ??= await _initDatabase();
Future<Database> _initDatabase() async {
Directory documentsDirectory = await getApplicationDocumentsDirectory();
String path = join(documentsDirectory.path, 'tasks.db');
return await openDatabase(
path,
version: 1,
onCreate: _onCreate,
);
}
Future _onCreate(Database db, int version) async {
await db.execute('''
CREATE TABLE IF NOT EXISTS "taskstable" (
"id" INTEGER,
"taskName" TEXT,
"isDone" INTEGER NOT NULL DEFAULT 0,
PRIMARY KEY("id" AUTOINCREMENT)
);
''');
}
Future<List<Tasksdb>> getTasks() async {
Database db = await instance.database;
var tasksQuery = await db.query(
'taskstable',
);
List<Tasksdb> taskList = tasksQuery.isNotEmpty
? tasksQuery.map((c) => Tasksdb.fromMap(c)).toList()
: [];
return taskList;
}
Future<int> add(Tasksdb task) async {
Database db = await instance.database;
return await db.insert('taskstable', {
'id': task.id,
'taskName': task.taskName,
'isDone': 0,
});
}
Future<int> update(Tasksdb task) async {
Database db = await instance.database;
return await db.update(
'taskstable',
task.toMap(),
where: "id = ?",
whereArgs: [task.id],
);
}
Future<int> updateIsDone(bool isDoneTodb) async {
Database db = await instance.database;
return await db.update(
'taskstable',
{
'isDone': isDoneTodb == true ? 1 : 0,
},
);
}
}
HomeScreen widget
class SqliteApp extends StatefulWidget {
const SqliteApp({Key? key}) : super(key: key);
#override
_SqliteAppState createState() => _SqliteAppState();
}
class _SqliteAppState extends State<SqliteApp> {
int? selectedId;
final textController = TextEditingController();
bool isDone = false;
#override
Widget build(BuildContext context) {
return MaterialApp(
home: Scaffold(
appBar: AppBar(
title: TextField(
controller: textController,
),
),
body: Center(
child: FutureBuilder<List<Tasksdb>>(
future: DatabaseHelper.instance.getTasks(),
builder: (BuildContext context,
AsyncSnapshot<List<Tasksdb>> snapshot) {
if (!snapshot.hasData) {
return const Center(child: Text('Loading...'));
}
return snapshot.data!.isEmpty
? const Center(child: Text('No tasks in List.'))
: ListView(
children: snapshot.data!.map((task) {
return Center(
child: Card(
color: selectedId == task.id
? Colors.green
: Colors.yellow,
child: ListTile(
trailing: Switch( //the problem is here, doesn't save to db
value: isDone,
onChanged: (val) async {
setState(() {
isDone = val;
});
await DatabaseHelper.instance
.updateIsDone(
isDone,
);
}),
title: Text(task.taskName),
onTap: () {
setState(() {
if (selectedId == null) {
textController.text = task.taskName;
selectedId = task.id;
} else {
textController.text = 'add something';
selectedId = null;
}
});
},
),
),
);
}).toList(),
);
}),
),
floatingActionButton: FloatingActionButton(
onPressed: () async {
await DatabaseHelper.instance.add(
Tasksdb(
taskName: textController.text,
isDone: false,
),
);
setState(() {
textController.clear();
selectedId = null;
});
},
),
),
);
}
}
I found the answer: (in case of if someone had the same question)
I removed the bool isDone from the material app widget, and instead of assigning the switch val to that bool I assigned it to database's task.isDone value. To avoid switch's auto trigger, I parsed the Taskdb to the updateIsDone function
Future<int> updateIsDone(Tasksdb task, bool isDoneTodb) async {
Database db = await instance.database;
return await db.update(
'taskstable',
{
'isDone': isDoneTodb == true ? 1 : 0,
},
where: "id = ?",
whereArgs: [task.id]);
}
...
Switch(
value: task.isDone,
onChanged: (val) async {
setState(() {
task.isDone = val;
});
await DatabaseHelper.instance
.updateIsDone(task, task.isDone);
});

"Warning database has been locked" warning with SQFlite and code stops. Why can I not query the table?

I'm having trouble querying a SQFlite db table in Flutter. I get the following warning several times:
I/chatty (32047): uid=10160(com.example.SQFLite_test) 1.ui identical 18498 lines 2
I/flutter (32047): Warning database has been locked for 0:00:10.000000. Make sure you always use the transaction
object for database operations during a transaction
I get the warning when calling the getClients() method to get all clients from the Client table. The main issue though is that it seems to freeze the code as well. Even when I only try to select the top 100, it still gives me the warning and it freezes and doesn't progress.
My db class helping me to init and manage the database:
class LogServiceTwo {
LogServiceTwo._();
static final LogServiceTwo logRepo = LogServiceTwo._();
static Database _database;
Future<Database> get database async {
if (_database != null) {
return _database;
}
var db = await openDb();
// if (db == null) {
// _database = await initDB();
// return _database;
// }
var hasClientTableB = await hasClientTable(db);
if (hasClientTableB) {
_database = db;
return _database;
}
// var backup = await restoreBackup(db);
// if (backup != null) {
// _database = backup;
// return _database;
// }
await createClientTable(db);
_database = db;
return _database;
}
Future createClientTable(Database db) async {
await db.execute("CREATE TABLE Client ("
"id INTEGER PRIMARY KEY,"
"first_name TEXT,"
"last_name TEXT,"
"blocked BIT"
")");
}
Future<bool> hasClientTable(Database db) async {
try {
var table = await db.query("Client");
return table != null;
} catch (e) {
return false;
}
}
Future<Database> openDb() async {
try {
var path = await getPersistentDbPath();
var db = await openDatabase(path, version: 1);
return db;
} catch (e) {
return null;
}
}
Future initDB() async {
var path = await getPersistentDbPath();
return await openDatabase(path, version: 1, onOpen: (db) {}, onCreate: (Database db, int version) async {
await db.execute("CREATE TABLE Client ("
"id INTEGER PRIMARY KEY,"
"first_name TEXT,"
"last_name TEXT,"
"blocked BIT"
")");
});
}
Future newClient(Client newClient) async {
final db = await database;
var res = await db.insert("Client", newClient.toMap());
return res;
}
Future newClients(List<Client> clients) async {
var clientMaps = clients.map((client) => client.toMap()).toList();
final db = await database;
clientMaps.forEach((clientMap) async {
await db.insert("Client", clientMap);
});
}
Future<Client> getClient(int id) async {
final db = await database;
var res = await db.query("Client", where: "id = ?", whereArgs: [id]);
return res.isNotEmpty ? Client.fromMap(res.first) : Null;
}
Future<List<Client>> getAllClients() async {
final db = await database;
var res = await db.query("Client");
List<Client> list = res.isNotEmpty ? res.map((c) => Client.fromMap(c)).toList() : [];
return list;
}
Future<List<Client>> getBlockedClients() async {
final db = await logRepo.database;
var res = await db.rawQuery("SELECT * FROM Client WHERE blocked=1");
List<Client> list = res.isNotEmpty ? res.toList().map((c) => Client.fromMap(c)) : null;
return list;
}
Future<List<String>> getTables() async {
var db = await logRepo.database;
var tableNames = (await db.query('sqlite_master', where: 'type = ?', whereArgs: ['table'])).map((row) => row['name'] as String).toList(growable: false);
return tableNames;
}
Future<String> getPersistentDbPath() async {
return await createPersistentDbDirecotry();
}
Future createPersistentDbDirecotry() async {
var externalDirectoryPath = await ExtStorage.getExternalStorageDirectory();
var persistentDirectory = "$externalDirectoryPath/db_persistent";
await createDirectory(persistentDirectory);
return "$persistentDirectory/persistent.db";
}
Future createDirectory(String path) async {
await (new Directory(path).create());
}
Future<bool> askForWritePermission() async {
var status = await Permission.storage.status;
if (!status.isGranted) {
status = await Permission.storage.request();
return status.isGranted;
}
return status.isGranted;
}
Future mockData() async {
var clients = ClientMocker.createClients();
await newClients(clients);
}
Future deleteAll() async {
var db = await database;
await db.rawDelete("DELETE FROM Client");
}
// Get all clients, throws warnings and stops proceeding in the code.
Future getClients() async {
try {
var db = await database;
return await db.rawQuery("SELECT * FROM Client");
} catch (e) {
print(e);
}
}
}
My main class calling the database service for testing purposes:
void main() {
runApp(MyApp());
}
class MyApp extends StatelessWidget {
// This widget is the root of your application.
#override
Widget build(BuildContext context) {
return MaterialApp(
title: 'Flutter Demo',
theme: ThemeData(
// This is the theme of your application.
//
// Try running your application with "flutter run". You'll see the
// application has a blue toolbar. Then, without quitting the app, try
// changing the primarySwatch below to Colors.green and then invoke
// "hot reload" (press "r" in the console where you ran "flutter run",
// or simply save your changes to "hot reload" in a Flutter IDE).
// Notice that the counter didn't reset back to zero; the application
// is not restarted.
primarySwatch: Colors.blue,
// This makes the visual density adapt to the platform that you run
// the app on. For desktop platforms, the controls will be smaller and
// closer together (more dense) than on mobile platforms.
visualDensity: VisualDensity.adaptivePlatformDensity,
),
home: MyHomePage(title: 'Flutter Demo Home Page'),
);
}
}
class MyHomePage extends StatefulWidget {
MyHomePage({Key key, this.title}) : super(key: key);
// This widget is the home page of your application. It is stateful, meaning
// that it has a State object (defined below) that contains fields that affect
// how it looks.
// This class is the configuration for the state. It holds the values (in this
// case the title) provided by the parent (in this case the App widget) and
// used by the build method of the State. Fields in a Widget subclass are
// always marked "final".
final String title;
#override
_MyHomePageState createState() => _MyHomePageState();
}
class _MyHomePageState extends State<MyHomePage> {
#override
void initState() {
// firstTest();
// secondTest();
thirdTest();
testText = "";
super.initState();
}
String testText;
#override
Widget build(BuildContext context) {
return Scaffold(
appBar: AppBar(
title: Text(widget.title),
),
body: Center(
// Center is a layout widget. It takes a single child and positions it
// in the middle of the parent.
child: Column(
children: [
Container(
width: MediaQuery.of(context).size.width,
height: MediaQuery.of(context).size.height,
child: Text(testText),
)
],
),
),
);
}
Future firstTest() async {
testText = "";
// var client = new Client(blocked: false, firstName: "Tobias", lastName: "Eliasson", id: null);
// await LogRepository.logRepo.newClient(client);
// await LogRepository.logRepo.newClient(client);
// await LogRepository.logRepo.newClient(client);
var clients = await LogRepository.logRepo.getAllClients();
clients.forEach((c) {
setState(() {
testText += "\n${c.toMap()}";
});
print(c.toMap());
});
setState(() {
testText += "Length of found clients: ${clients.length.toString()}";
});
var success = await LogRepository.logRepo.saveBackup();
print(success);
}
Future secondTest() async {
try {
await LogRepository.logRepo.deleteAll();
await LogRepository.logRepo.mockData();
var a = DateTime.now();
print("Saving backup $a");
var backupSuccess = await LogRepository.logRepo.saveBackup();
print("Backup success: $backupSuccess");
var b = DateTime.now();
print("Saved backup:${a.difference(b)}");
} catch (e) {
print("Error!!!");
print(e);
}
}
Future thirdTest() async {
await LogServiceTwo.logRepo.database;
await LogServiceTwo.logRepo.mockData();
var clients = await LogServiceTwo.logRepo.getClients();
print(clients.length);
}
}
As far as I can see, I await all db operations and only use on db object to access it so there shouldn't be any weird parallell access going on. Maybe you find an error somewhere I'm missing though. In case you wonder why I create the database in external memory, is that the database needs to be persistent and saved when uninstalling the app or updating it.
Thanks!
I found the problem and learnt a lesson. In short, follow conventions and best practices when accessing a database. The problem was that I inserted one client at the time inside the method:
Future newClients(List<Client> clients) async {
var clientMaps = clients.map((client) => client.toMap()).toList();
final db = await database;
clientMaps.forEach((clientMap) async {
await db.insert("Client", clientMap);
});
}
When inserting or doing many db operations at the same moment, use batch and commit instead like this:
Future newClients(List<Client> clients) async {
var clientMaps = clients.map((client) => client.toMap()).toList();
final db = await database;
var batch = db.batch();
clientMaps.forEach((clientMap) async {
batch.insert("Client", clientMap);
});
await batch.commit(noResult: true);
}
With the batch and commit solution I could insert 90 000 clients on first try with no errors and could query them all after.

Truffle console command result is not the same as the react redux async/await solidity contract method

I have the following solidity contract
mapping (string => bool) private proofs;
mapping (address => string[]) public owns;
function registerAsset(string memory assetHash) public {
proofs[assetHash] = true;
owns[msg.sender].push(assetHash);
}
function checkIfRegistered(string memory assetHash) public view returns (bool) {
return proofs[assetHash];
}
function getSize(address key) public view returns (uint){
return owns[key].length;
}
function getAssets(address key) public view returns (string[] memory){
return owns[key];
}
After I call registerAsset through async/await as below
async function registerAsset(PoExContract, assetHash) {
const result = PoExContract.deployed().then((poe) => {
return poe.registerAsset(assetHash)
})
const transaction = (result !== null) ? result : null
return transaction
}
export function register() {
return async (dispatch, getState) => {
const { poExContract } = getState().contract
const { assetHash } = getState().asset
const transaction = await registerAsset(poExContract, assetHash)
if (transaction) {
dispatchAssetCreated(transaction, assetHash, dispatch)
} else {
dispatchCreationError(dispatch)
}
}
and call the getAssets method,
async function getRegisteredAssets(PoExContract, account) {
const regsiterdAssets = PoExContract.deployed().then((poe) => {
return poe.getAssets(account)
})
return regsiterdAssets
}
export function getAssets(defaultAccount){
return async(dispatch, getState) =>{
const { poExContract } = getState().contract
let registeredAssets = await getRegisteredAssets(poExContract,defaultAccount)
console.log(registeredAssets)
dispatchAssets(registeredAssets, dispatch)
}
I get an array with empty String at the console.log(registeredAssets)
[" "]
Where as the truffle console like
truffle(development)> let instance = await PoExContract.deployed()
undefined
truffle(development)> let assets = await instance.getAssets('0x3E7Ff8055f225a019144365a3714c43c2a831e24')
undefined
truffle(development)> assets
[ 'fb90f1afe1de770fe175af0e27a1f85901f277005bfffb8ee502a7304e85b671' ]
I dont have any clue why the JS async/await returns array with empty string, where as the same method on truffle console returns correct result.
[ 'fb90f1afe1de770fe175af0e27a1f85901f277005bfffb8ee502a7304e85b671' ]
When i did further investigation, I found that only the recently registered asset is not included in the getAssets list, but all the previous registrations returns properly.
Well, returning an Array of strings from Solidity contracts is still in its infancy when I used the encoder version 2
pragma experimental ABIEncoderV2;
So, I replaced my earlier solidity contract method
function getAssets(address key) public view returns (string[] memory assets){
assets = new string[](owns[key].length);
for (uint i=0; i<owns[key].length; i++){
assets[i] = owns[key][i];
}
}
with the following one as STEP-1
function getAsset(address key, uint index) public view returns (string memory asset){
asset = owns[key][index];
}
and get each asset (as STEP-2) by
async function getRegisteredAsset(ProofOfExContract, account, index) {
const poe = await ProofOfExContract.deployed()
const registeredAsset = await poe.getAsset(account, index)
return registeredAsset
}
and loop through the react async/await like the below as STEP-3
for (var i=0;i<numberOfAssets;i++){
const asset = await getRegisteredAsset(proofOfExContract, defaultAccount, i)
dispatchAccountAsset(asset,dispatch)
}
to get the actual expected result that is same as that of the Truffle console

Resources