How to return json data to a react state?

后端 未结 1 1970
囚心锁ツ
囚心锁ツ 2020-12-12 05:22

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

相关标签:
1条回答
  • 2020-12-12 06:12

    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);
          })
      }
    
    0 讨论(0)
提交回复
热议问题