0

I have a react component that makes a post to an express server (my own server). The server uses web3 to sign a transaction on Ethereum. Once the transaction is included in a block, a json object is returned to the server. It looks like this:

{ blockHash: '0xcd08039bac40e2865886e8f707ce9b901978c339d3abb81516787b0357f53fbd',
  blockNumber: 4611028,
 ...other data...
  transactionHash: '0x12c65523743ed169c764553ed2e0fb2af1710bb20a41b390276ffc2d5923c6a9',
  transactionIndex: 1 }

I need to store the transactionHash into the state of the above component. I have been searching for 2 days and am probably missing something very obvious.

Is this server-side or client-side code?

Do I need to learn and use async because of the inherent time delay in talking to Ethereum?

1 Answer 1

2

To make the post request, you would have to perform this one the client via the componentDidMount, and then store the response as you would normally. You can find full examples here: https://reactjs.org/docs/faq-ajax.html on the react page.

fetch("https://api.example.com/items")
    .then(res => res.json())
    .then(response => this.setState(response));

You would have to adjust the fetch operation to be a post request but you can find more information related to fetching here: https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch

fetch("https://api.example.com/items", {
  method: 'POST',
  body: JSON.stringify(data),
  headers:{
    'Content-Type': 'application/json'
  }
})
.then(res => res.json())
.then(response => this.setState(response))
.catch(error => console.error('Error:', error));

Edit (example with Axios):

componentDidMount() {
    axios.get("https://api.example.com/items")
      .then(res => {
        const items = res.data;
        this.setState(items);
      })
  }
Sign up to request clarification or add additional context in comments.

5 Comments

Thank you for the lead. I am currently using axios so maybe I will need to modify. Just give me a day or two to accept. I appreciate it :)
I have gone and updated the example to contain the axios library.
Thank you, that did store items in the state. I am only wanting to store transactionHash and nothing more. Do you think I should open a separate question?
You can then just use JS dot notation to access the value. setState({ transaction: items.transactionHash });
That is not working unfortunately. I've opened a new thread which has got me down a rabbit hole... stackoverflow.com/questions/53749081/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.