0

I am trying to return a matrix in React that I get from a contract function.

This is the function that resonate the matrix:

    int[][] public publicData;

    function handleAddData(int[] memory data) public {

    publicData.push(data);

    }

   function getData() public returns(int[][] memory data) {
    return publicData;
   }

I'm using solidity version 0.5.

In React, I try to get the data as follows from the app.js file:

import React, {Component} from 'react';
import logo from './logo.svg';
import './App.css';
import web3 from './web3';
import datastorage from './datastorage';

class App extends Component {

  state = {
    data: []
  };

  async componentDidMount() {
    const data = await datastorage.methods.getData().call();
    this.setState({ data });
  }

  render() {

    return (
      <div>
        <h2>Data: </h2>
        <p>Aqui: {this.state.data}</p>
      </div>
  );

}
}

export default App;

If i use {this.state.data.length} it returns me the size, but when I try to get the data inside the matrix, I can't.

1

Add the following functions in your contract, an then use them in your application:

function getLength() public view returns (uint) {
    return publicData.length;
}

function getDataLength(uint index) public view returns (uint) {
    return publicData[index].length;
}

Usage example:

const length = await datastorage.methods.getLength();
for (let i = 0; i < length; i++) {
    const dataLength = await datastorage.methods.getDataLength(i);
    for (let j = 0; j < dataLength; j++) {
        const item = await datastorage.methods.publicData(i, j);
        console.log(`publicData[${i}][${j}] = ${item}`);
    }
}
| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.