1

Im creating a function that adds a new book

//add book external
 function addBook(string memory _name, bool _promoted) external returns (uint) {
   uint pdate = block.timestamp;
   uint bookId = bookList.length;
   bookList.push(Book(bookId, _name, 0, pdate, _promoted));
   bookToOwner[bookId] = msg.sender;

//return the id of the created book return apbookIdpId; }

This is returning me the

enter image description here

So how can I get the id of the just created book? I tested different return values like int etc and looks like is always returning the full json

nonyck82
  • 11
  • 1

2 Answers2

0

If you're using ethers.js, you could use the following line:

const apbookIdpId = await contract.callStatic.addBook(name, promoted)

And place it right above the actual call:

await contract.addBook(name, promoted)

Ahmed Ihsan Tawfeeq
  • 4,524
  • 2
  • 19
  • 47
0

The addBook function modifies the state of the contract, which means that the transaction calling that function will be broadcasted through the network, pay gas, and will be mined and included in a block. All this will be asynchronous, so, you will not get the response right away.

You will need to emit an event containing the data that you need and then subscribe to that event.

For example:

event BookAdded(uint bookId);

function addBook(string memory _name, bool _promoted) external returns (uint) { uint pdate = block.timestamp; uint bookId = bookList.length; bookList.push(Book(bookId, _name, 0, pdate, _promoted)); bookToOwner[bookId] = msg.sender;

emit BookAdded(apbookIdpId);

//return the id of the created book return apbookIdpId; }

And subscribe to it like:

const subscription = web3.eth.subscribe('logs', {
    address: '0x123456..', // The smart contract address
    topics: ['0x12345...'] // The topics of your event
}, function(error, result){
    if (!error)
        console.log(result);
});

I answered a similar question yesterday with details. For more details, check this answer: How can I get transaction result?

Jeremy Then
  • 4,599
  • 3
  • 5
  • 28