How to Read an Array in Solidity With Web3

Y'all are using an out of date browser. Information technology may not display this or other websites correctly.
You should upgrade or apply an alternative browser.

[Solved] Is in that location a way to display a Solidity assortment of structs in React?

  • Thread starter Kamil
  • Start date
  • #1

Kamil Asks: Is there a way to brandish a Solidity assortment of structs in React?
I am trying to display the contents of a Solidity array of structs in a React front-end.

This is my Solidity smart contract. I've created a function which returns the length of the array in question.

Code:

                            pragma solidity ^0.viii.0;  contract Project {      struct Person {         cord name;         string description;     }          Person[] public people;      function getPersonCount() public view returns (uint) {         render people.length;     }  }                          

Here is my front-end React code:

Code:

                            import React from "react"; import Web3 from './web3'; import { ABI } from './ABI'; import { contractAddr } from './Address';  const web3 = new Web3(Web3.givenProvider); const ContractInstance = new web3.eth.Contract(ABI, contractAddr);  const NewPerson = () => {      let personCount = 0;      personCount = ContractInstance.methods.getPersonCount().call();      return (         personCount     ); };  export default NewPerson;                          

When I run that front-end code, I get this error message:

Error: Objects are not valid as a React child (establish: [object Promise]). If you meant to render a drove of children, use an array instead.

Reading answers to questions on here, I thought the trouble might be that I demand to call my Solidity function asynchronously then that I tin can return the output of the function rather than a promise. I tried re-writing my React code like so:

Code:

                            import React from "react"; import Web3 from './web3'; import { ABI } from './ABI'; import { contractAddr } from './Accost';  const web3 = new Web3(Web3.givenProvider); const ContractInstance = new web3.eth.Contract(ABI, contractAddr);  const NewPerson = () => {      let personCount = 0;      async role handlePerson() {         personCount = await ContractInstance.methods.getPersonCount().telephone call();     }      handlePerson();      return (         personCount     ); };  export default NewPerson;                          

This did not trigger an error, only instead returned 0 (suggesting that the handlePerson office did not even run).

I then tried another approach:

Code:

                            import React from "react"; import Web3 from './web3'; import { ABI } from './ABI'; import { contractAddr } from './Accost';  const web3 = new Web3(Web3.givenProvider); const ContractInstance = new web3.eth.Contract(ABI, contractAddr);  const NewPerson = () => {       let personCount = 0;      async office handlePerson() {         personCount = await ContractInstance.methods.getPersonCount().telephone call();                  return (             personCount         );     }     return (         handlePerson()     );  };  export default NewPerson;                          

This gave me the same error message I got the first time around:

Error: Objects are not valid as a React child (establish: [object Promise]). If you meant to render a collection of children, use an assortment instead.

I'd be grateful if anyone has any advice to offer, or if anyone has experienced something similar. My goal is to then iterate through the assortment to brandish all of its elements, just and so far I don't fifty-fifty seem to be able to display the number of elements in it. It'south particularly strange since I'chiliad successfully able to call other functions from my smart contract via the React front end-finish. Many thanks in advance!

Update:​

Many thank you to MrFrenzoid for the help. I've re-written my forepart-end code and so that I am at present able to query individual elements of the Solidity array:

Lawmaking:

                            import React from "react"; import Web3 from './web3'; import { ABI } from './ABI'; import { contractAddr } from './Address';  const web3 = new Web3(Web3.givenProvider); const ContractInstance = new web3.eth.Contract(ABI, contractAddr);  const NewPerson = () => {          // Using hard-coded personCount for testing purposes     let personCount = 70;     let people = [];      async office handlePeople() {         for (allow i=0; i<personCount; i++) {             const person = await ContractInstance.methods.people(i).call();             people.push(person);         }         console.log(people);     }      handlePeople();      return (         null     );  };  consign default NewPerson;                          

This returns the contents of the array in the console, as expected. The issue I'g withal having is querying the length of the Solidity array, so that I can use that to compute personCount (rather than using a difficult-coded value as I practice higher up).

Lawmaking:

                            import React from "react"; import Web3 from './web3'; import { ABI } from './ABI'; import { contractAddr } from './Accost';  const web3 = new Web3(Web3.givenProvider); const ContractInstance = new web3.eth.Contract(ABI, contractAddr);  const NewPerson = () => {      allow people = [];      async function handlePersonCount() {         const personCount = look ContractInstance.methods.getPersonCount().call();         console.log(personCount);     }      async office handlePeople() {         for (let i=0; i<personCount; i++) {             const person = await ContractInstance.methods.people(i).call();             people.button(person);         }         panel.log(people);     }      handlePersonCount();     handlePeople();      return (         zero     );  };  export default NewPerson;                          

When I run handlePersonCount(), I get this error message: error message

The reason I'1000 taking this approach at all is because I'k seemingly unable to query the entire Solidity assortment at once, and instead demand to query one chemical element at a time.

SolveForum.com may not be responsible for the answers or solutions given to whatever question asked by the users. All Answers or responses are user generated answers and we practice not accept proof of its validity or definiteness. Please vote for the respond that helped you in order to help others find out which is the most helpful answer. Questions labeled as solved may be solved or may non exist solved depending on the type of question and the appointment posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your response here to help other visitors similar you. Thank you, solveforum.

/whats-new/news-feed
  • a_fr159
  • Applied science Forum
  • Replies: 0

a_fr159 Asks: How to become second table fields in a bring together using querybuilder
Is possible to get a filed of the second table of a join using doctrine queryBuilder

Code:

                                                      $qb = $this->createQueryBuilder('gt')                 ->select(['gt','gtst'])                 ->distinct()                 ->bring together('gt.gtTrackings', 'gtst')                 ->Where('gt.status = :not_filled')                 ->andWhere('gtst.status = :finished)                 ->setParameter('not_filled', $status1)                 ->setParameter('finished', $status2)                 ->orderBy('gtst.created', 'ASC');                        

I need a field named created from gtTrackings table and I don't know how

SolveForum.com may non exist responsible for the answers or solutions given to whatsoever question asked by the users. All Answers or responses are user generated answers and we do not have proof of its validity or correctness. Please vote for the respond that helped you in order to aid others find out which is the well-nigh helpful answer. Questions labeled as solved may be solved or may non exist solved depending on the type of question and the date posted for some posts may exist scheduled to be deleted periodically. Practice not hesitate to share your response here to help other visitors like you. Give thanks you, solveforum.

  • Никита Закорючкин
  • Technology Forum
  • Replies: 0

Никита Закорючкин Asks: /usr/bin/ld: cannot find during linking g++
This question has already been hither and so many times. But I didn't detect the respond.

I have this .cpp file

Lawmaking:

                          #include <clickhouse/customer.h> #include <iostream> using namespace clickhouse;   int principal(){     /// Initialize client connection.     Client customer(ClientOptions().SetHost("localhost"));      client.Select("SELECT l.a, l.b from table", [] (const Cake& block)         {             for (size_t i = 0; i < cake.GetRowCount(); ++i) {                 std::cout << cake[0]->As<ColumnUInt64>()->At(i) << " "                         << block[1]->As<ColumnString>()->At(i) << "\n";             }         }     );     return 0; }                        

and I accept instantiated And so library, like written here. subsequently that i got the following structure of /usr/local/lib directory:

Lawmaking:

                          ~/$ ls /usr/local/lib >>libclickhouse-cpp-lib-static.a  libclickhouse-cpp-lib.and so                        

in next stride I trying execute compilation with g++

Code:

                          ~/$ g++ run.cpp -std=c++17 -o result -llibclickhouse-cpp-lib -50/usr/local/lib >>/usr/bin/ld: cannot find -llibclickhouse-cpp-lib >>collect2: error: ld returned i exit status                        

I don't know what hinders create links.

thank You for Your assist!

SolveForum.com may not exist responsible for the answers or solutions given to whatever question asked by the users. All Answers or responses are user generated answers and nosotros do not have proof of its validity or correctness. Please vote for the answer that helped you in order to assist others observe out which is the nearly helpful answer. Questions labeled as solved may be solved or may non be solved depending on the type of question and the engagement posted for some posts may be scheduled to exist deleted periodically. Exercise non hesitate to share your response here to help other visitors like you. Thanks, solveforum.

  • water_enjoyer
  • Engineering science Forum
  • Replies: 0

water_enjoyer Asks: In PostgreSQL, how do I read in tab-delimited data that contains a infinite?
Postgres thinks my last column of information, containing two words separated past a infinite, is ii columns of information.

My query:

Code:

                          COPY public.avails (id, name, model, category, brand) FROM '/home/123_COPY.sql' DELIMITER Due east'\t' CSV HEADER;                        

The mistake in PgAdmin:

Code:

                          ERROR:  actress data after last expected column CONTEXT:  Copy assets, line 2: "a11bc222-d3ee-4f55-gg6h-777i88j9k00 DB-DA-AB22-10   Inspiron    Tech    Desktop Dell" SQL state: 22P04                        

SolveForum.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we practise non have proof of its validity or correctness. Delight vote for the answer that helped you in order to help others find out which is the near helpful answer. Questions labeled as solved may be solved or may non be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Exercise non hesitate to share your response here to help other visitors like you lot. Thank you, solveforum.

  • Ehsan Akbar
  • Applied science Forum
  • Replies: 0

Ehsan Akbar Asks: is there whatsoever func in protobuf in .net that operate like tryparse
I have this part of code :

Code:

                                                      MessageParser<T> parser = new(() => new T());         var cr = c.Consume(cts.Token);         var msg = parser.ParseFrom(cr.Message.Value);                        

My code reads messages from Kafka some messages are in protobuf type and some are in json ,But In this code I should read protobuf messages ,so I need some thing similar tryparse in protobuf base class to just read those message that are in protobuf type .

SolveForum.com may non exist responsible for the answers or solutions given to any question asked past the users. All Answers or responses are user generated answers and we do non have proof of its validity or definiteness. Please vote for the answer that helped you in society to help others find out which is the most helpful reply. Questions labeled as solved may be solved or may not be solved depending on the blazon of question and the engagement posted for some posts may be scheduled to exist deleted periodically. Do not hesitate to share your response here to help other visitors like you. Thanks, solveforum.

  • Ludema63
  • Engineering Forum
  • Replies: 0

Ludema63 Asks: how to delete a production from the cart?
through this button I would like to delete a product from the cart listing

Code:

                          <button id="btn_delete" class="label label-main" data - ISBN=@x.ISBN onclick="location.href='@Url.Activity("Remove ", "AddToCart ", x)'">Rimuovi</button>                        

I think I should not use @Url.Activity (besides because I have no Remove view) I would just like to invoke the Remove method that I created in the controller and that it worked.

Code:

                          public ActionResult Remove(Libro mo)         {                 List<Libro> li = (List<Libro>)Session["cart"];                 li.RemoveAll(10 => x.ISBN == mo.ISBN);                 Session["cart"] = li;                 Session["count"] = Catechumen.ToInt32(Session["count"]) - 1;                      return RedirectToAction("Myorder", "AddToCart");         }                        

SolveForum.com may not be responsible for the answers or solutions given to any question asked past the users. All Answers or responses are user generated answers and we practice not have proof of its validity or correctness. Delight vote for the reply that helped yous in club to help others find out which is the most helpful respond. Questions labeled every bit solved may be solved or may non be solved depending on the blazon of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your response here to help other visitors like you. Cheers, solveforum.

  • Serdar K.
  • Technology Forum
  • Replies: 0

Serdar K. Asks: C linked listing define how to reimplement a list
Hi this is probably a stupid question to enquire with a simple solution simply I just can't find an answer in the internet.

So I was exercising for an test and worked on an assignment. The program has the job to find out what the value in the center of a linked list is (if the length of the listing is an odd number)

The structdef is:

Code:

                          typedef struct IntList IntList; struct IntList {     int value;     IntList* next; };                        

and my verbal problem correct now is that I get a sectionalisation fault when I endeavor using:

I desire to go stride past pace in a loop to go to the wished listing at the nth position (the center) of the linked list.

Someone knows how I have to rewrite this? If you need more than Information to aid just say so and I will explicate more than.

SolveForum.com may not be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do not take proof of its validity or definiteness. Please vote for the answer that helped you in order to assistance others notice out which is the most helpful answer. Questions labeled as solved may exist solved or may not be solved depending on the blazon of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your response hither to assistance other visitors similar you. Cheers, solveforum.

  • bearding
  • Technology Forum
  • Replies: 0

bearding Asks: Society the Large-O function growth charge per unit
n + 0.001n^5, nlog(n^2), ii^(n/2), north^3, log n, sqrt(n) + log n, five log(n+100)^10, (3/2)^n, (north-two)!, n^two ++ log^2 n.

I desire to order these function by Big-O. The following is how I eliminate n

SolveForum.com may not be responsible for the answers or solutions given to any question asked past the users. All Answers or responses are user generated answers and we do not accept proof of its validity or correctness. Delight vote for the answer that helped you lot in social club to aid others find out which is the almost helpful respond. Questions labeled equally solved may be solved or may non exist solved depending on the type of question and the engagement posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your response hither to aid other visitors like you. Cheers, solveforum.

  • KW781
  • Technology Forum
  • Replies: 0

KW781 Asks: How to add firebase SDK to gradle java project?
And so I'm developing a Java app that I desire to connect to a firestore databse. I've copy-pasted the most upwards to appointment Firebase SDK and added the following dependency to my build.gradle file.

Code:

                          implementation 'com.google.firebase:firebase-admin:8.one.0'                        

I then rebuilt my project and wrote the following class that imports the com.google.firebase.FirebaseApp module.

Code:

                          packet FirebaseConnectivity;  import java.io.FileInputStream; import com.google.firebase.FirebaseApp;   public course FirebaseInitailise {     public void Initialise() {         FileInputStream serviceAccount =                 new FileInputStream("path/to/serviceAccountKey.json");          FirebaseOptions options = new FirebaseOptions.Builder()                 .setCredentials(GoogleCredentials.fromStream(serviceAccount))                 .build();          FirebaseApp.initializeApp(options);     } }                        

Nevertheless, IntelliJ is maxim that information technology can't import the module and that in my import statement 'google' is unecognised, even though I've added the dependency to my build.gradle. Anyone know a gear up to this?

SolveForum.com may non be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we do non take proof of its validity or definiteness. Please vote for the answer that helped you in order to help others detect out which is the nearly helpful reply. Questions labeled as solved may be solved or may non be solved depending on the type of question and the date posted for some posts may be scheduled to be deleted periodically. Do not hesitate to share your response here to help other visitors like yous. Thank you, solveforum.

  • Emman
  • Technology Forum
  • Replies: 0

Emman Asks: How to drop null elements but not undefined when using `arr.flatMap((f) => f ?? [])`?
I've written a role that removes nil values from an array:

Code:

                          const dropNull = <T,>(arr: T[]): T[] => {     return arr.flatMap((f) => f ?? []); // depends >= ES2019 };                        

For example:

Lawmaking:

                          const myArr1 = ['foo', 'bar', 'baz', null] const output1 = dropNull(myArr1)  console.log(output1) // => ["foo", "bar", "baz"]                        

However, I realized that it also removes undefined values.

Lawmaking:

                          const myArr2 = ['foo', 'bar', 'baz', null, undefined] const output2 = dropNull(myArr2) console.log(output2) // => ["foo", "bar", "baz"]                        

Is at that place a way to just tweak the current dropNull() in club to remove nothing just not undefined? That is, I know I could have re-written the function as:

Code:

                          const dropNull2 = <T,>(arr:T[]): T[] => {     return arr.filter(element => element !== zip) }                        

Only I like the arr.flatMap((f) => f ?? []) mode. Is in that location a small change to information technology so information technology will drib simply nix but non undefined?

TS playground

SolveForum.com may non be responsible for the answers or solutions given to any question asked by the users. All Answers or responses are user generated answers and we practice not take proof of its validity or correctness. Please vote for the answer that helped you in club to assist others find out which is the most helpful reply. Questions labeled as solved may exist solved or may non be solved depending on the blazon of question and the appointment posted for some posts may exist scheduled to exist deleted periodically. Do not hesitate to share your response here to assistance other visitors like you. Thank yous, solveforum.

  • Jakobkubek
  • Engineering Forum
  • Replies: 0

Jakobkubek Asks: How to get rid of the first comma in Python

Code:

                                                      tags = ProductInStore.objects.get(id=product_in_store_id).product.tags.values_list('proper name', flat=Truthful)         converted_list = listing(tags)         tags_string = ''         for tags in converted_list:             tags_string += ',' + tags         return tags_string                        

The output is

Code:

                          ,tag1,tag2,tag3,tag4,tag5                        

simply i'd similar to get rid of the kickoff comma. Practise you take any idea how to do it?

SolveForum.com may not be responsible for the answers or solutions given to whatsoever question asked by the users. All Answers or responses are user generated answers and we do not accept proof of its validity or definiteness. Please vote for the answer that helped y'all in order to help others find out which is the near helpful respond. Questions labeled as solved may exist solved or may not be solved depending on the type of question and the date posted for some posts may exist scheduled to be deleted periodically. Do not hesitate to share your response here to assist other visitors similar you. Thanks, solveforum.

kovacsthiss1950.blogspot.com

Source: https://solveforums.msomimaktaba.com/threads/solved-is-there-a-way-to-display-a-solidity-array-of-structs-in-react.47010/

0 Response to "How to Read an Array in Solidity With Web3"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel