reactjs fetch PUT value and pass value to state











up vote
1
down vote

favorite












How to re-fetch after <code>PUT</code>



class Mycomponent extends Component {
state = {
text: null
}

componentDidMount() {
fetch("http://localhost:3000/books/4")
.then(response => response.json())
.then(data => this.setState({ text: data.title // this data.value is "Learn Javascript" }));
}

fetchPUT(val) {
fetch("http://localhost:3000/books/4", {
method: "PUT",
headers: {
"Content-Type": "application/json; charset=utf-8"
},
body: JSON.stringify({ value: val })
}).then(e => console.log(e));
}

onMouseDown = e => {
this.setState({
text: this.refs.myinput.value,
});
this.fetchPUT(this.refs.myinput.value);
};
render() {
const { text } = this.state;
return (
<div>
<input
type="text"
value={text}
onMouseLeave={this.onMouseLeave}
ref="myinput"
/>
</div>
)
}
}


I'd like to sync this.text whenever I click button to PUT the value. so the flow is to fetch first then change value, click button PUT value, after PUT, then fetch again










share|improve this question


























    up vote
    1
    down vote

    favorite












    How to re-fetch after <code>PUT</code>



    class Mycomponent extends Component {
    state = {
    text: null
    }

    componentDidMount() {
    fetch("http://localhost:3000/books/4")
    .then(response => response.json())
    .then(data => this.setState({ text: data.title // this data.value is "Learn Javascript" }));
    }

    fetchPUT(val) {
    fetch("http://localhost:3000/books/4", {
    method: "PUT",
    headers: {
    "Content-Type": "application/json; charset=utf-8"
    },
    body: JSON.stringify({ value: val })
    }).then(e => console.log(e));
    }

    onMouseDown = e => {
    this.setState({
    text: this.refs.myinput.value,
    });
    this.fetchPUT(this.refs.myinput.value);
    };
    render() {
    const { text } = this.state;
    return (
    <div>
    <input
    type="text"
    value={text}
    onMouseLeave={this.onMouseLeave}
    ref="myinput"
    />
    </div>
    )
    }
    }


    I'd like to sync this.text whenever I click button to PUT the value. so the flow is to fetch first then change value, click button PUT value, after PUT, then fetch again










    share|improve this question
























      up vote
      1
      down vote

      favorite









      up vote
      1
      down vote

      favorite











      How to re-fetch after <code>PUT</code>



      class Mycomponent extends Component {
      state = {
      text: null
      }

      componentDidMount() {
      fetch("http://localhost:3000/books/4")
      .then(response => response.json())
      .then(data => this.setState({ text: data.title // this data.value is "Learn Javascript" }));
      }

      fetchPUT(val) {
      fetch("http://localhost:3000/books/4", {
      method: "PUT",
      headers: {
      "Content-Type": "application/json; charset=utf-8"
      },
      body: JSON.stringify({ value: val })
      }).then(e => console.log(e));
      }

      onMouseDown = e => {
      this.setState({
      text: this.refs.myinput.value,
      });
      this.fetchPUT(this.refs.myinput.value);
      };
      render() {
      const { text } = this.state;
      return (
      <div>
      <input
      type="text"
      value={text}
      onMouseLeave={this.onMouseLeave}
      ref="myinput"
      />
      </div>
      )
      }
      }


      I'd like to sync this.text whenever I click button to PUT the value. so the flow is to fetch first then change value, click button PUT value, after PUT, then fetch again










      share|improve this question













      How to re-fetch after <code>PUT</code>



      class Mycomponent extends Component {
      state = {
      text: null
      }

      componentDidMount() {
      fetch("http://localhost:3000/books/4")
      .then(response => response.json())
      .then(data => this.setState({ text: data.title // this data.value is "Learn Javascript" }));
      }

      fetchPUT(val) {
      fetch("http://localhost:3000/books/4", {
      method: "PUT",
      headers: {
      "Content-Type": "application/json; charset=utf-8"
      },
      body: JSON.stringify({ value: val })
      }).then(e => console.log(e));
      }

      onMouseDown = e => {
      this.setState({
      text: this.refs.myinput.value,
      });
      this.fetchPUT(this.refs.myinput.value);
      };
      render() {
      const { text } = this.state;
      return (
      <div>
      <input
      type="text"
      value={text}
      onMouseLeave={this.onMouseLeave}
      ref="myinput"
      />
      </div>
      )
      }
      }


      I'd like to sync this.text whenever I click button to PUT the value. so the flow is to fetch first then change value, click button PUT value, after PUT, then fetch again







      javascript reactjs






      share|improve this question













      share|improve this question











      share|improve this question




      share|improve this question










      asked Nov 11 at 6:46









      olo

      2,070113063




      2,070113063
























          1 Answer
          1






          active

          oldest

          votes

















          up vote
          2
          down vote



          accepted










          You don't have to fetch the data from backend to synchronise the value with the current text. Instead use setState callback in your onMouseDown as:



          onMouseDown = e => {
          this.setState({
          text: this.refs.myinput.value,
          }, () => {
          this.fetchPUT(this.refs.myinput.value);
          });
          };


          Here the state will be set before it makes a put call and as you're having the updated value, you don't have to fetch the value. When the component is unmounted and mounts again, it will fetch the updated value from your componentDidMount.



          Read more here



          Also



          In the render function, use onChange instead of onMouseDown (Which you're not even using) because that would be less confusing. Use debounce so that you don't have to make many API calls on every change.



          onChange = _.debounce((event) => {
          const text = event.target.value;
          this.setState({text}, () => {
          this.fetchPUT(text);
          })
          }, 500)

          render() {
          const { text } = this.state;
          return (
          <div>
          <input
          type="text"
          value={text}
          onChange={this.onChange}
          />
          </div>
          )
          }





          share|improve this answer























          • Thank you! But if I want to sync, what lifecycle method should I use?
            – olo
            Nov 11 at 9:05






          • 1




            You can use componentWillReceiveProps or componentDidUpdate. As React might deprecate componentWill* methods, you should use componentDidUpdate. You can read the documentation of React which is wonderful
            – Ajay Gaur
            Nov 11 at 9:08










          • Many thanks for you answer!
            – olo
            Nov 11 at 9:09










          • I am having erros on callback to use this.fetchPUT(this.refs.myinput.value); either to make a var/const or use text straight away can solve the issue. onMouseDown = e => { const _value = this.refs.myinput.value; this.setState( { text: _value, isEditable: false }, () => { this.fetchPUT(_value); } ); };
            – olo
            Nov 11 at 9:19













          Your Answer






          StackExchange.ifUsing("editor", function () {
          StackExchange.using("externalEditor", function () {
          StackExchange.using("snippets", function () {
          StackExchange.snippets.init();
          });
          });
          }, "code-snippets");

          StackExchange.ready(function() {
          var channelOptions = {
          tags: "".split(" "),
          id: "1"
          };
          initTagRenderer("".split(" "), "".split(" "), channelOptions);

          StackExchange.using("externalEditor", function() {
          // Have to fire editor after snippets, if snippets enabled
          if (StackExchange.settings.snippets.snippetsEnabled) {
          StackExchange.using("snippets", function() {
          createEditor();
          });
          }
          else {
          createEditor();
          }
          });

          function createEditor() {
          StackExchange.prepareEditor({
          heartbeatType: 'answer',
          convertImagesToLinks: true,
          noModals: true,
          showLowRepImageUploadWarning: true,
          reputationToPostImages: 10,
          bindNavPrevention: true,
          postfix: "",
          imageUploader: {
          brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
          contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
          allowUrls: true
          },
          onDemand: true,
          discardSelector: ".discard-answer"
          ,immediatelyShowMarkdownHelp:true
          });


          }
          });














          draft saved

          draft discarded


















          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53246471%2freactjs-fetch-put-value-and-pass-value-to-state%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown

























          1 Answer
          1






          active

          oldest

          votes








          1 Answer
          1






          active

          oldest

          votes









          active

          oldest

          votes






          active

          oldest

          votes








          up vote
          2
          down vote



          accepted










          You don't have to fetch the data from backend to synchronise the value with the current text. Instead use setState callback in your onMouseDown as:



          onMouseDown = e => {
          this.setState({
          text: this.refs.myinput.value,
          }, () => {
          this.fetchPUT(this.refs.myinput.value);
          });
          };


          Here the state will be set before it makes a put call and as you're having the updated value, you don't have to fetch the value. When the component is unmounted and mounts again, it will fetch the updated value from your componentDidMount.



          Read more here



          Also



          In the render function, use onChange instead of onMouseDown (Which you're not even using) because that would be less confusing. Use debounce so that you don't have to make many API calls on every change.



          onChange = _.debounce((event) => {
          const text = event.target.value;
          this.setState({text}, () => {
          this.fetchPUT(text);
          })
          }, 500)

          render() {
          const { text } = this.state;
          return (
          <div>
          <input
          type="text"
          value={text}
          onChange={this.onChange}
          />
          </div>
          )
          }





          share|improve this answer























          • Thank you! But if I want to sync, what lifecycle method should I use?
            – olo
            Nov 11 at 9:05






          • 1




            You can use componentWillReceiveProps or componentDidUpdate. As React might deprecate componentWill* methods, you should use componentDidUpdate. You can read the documentation of React which is wonderful
            – Ajay Gaur
            Nov 11 at 9:08










          • Many thanks for you answer!
            – olo
            Nov 11 at 9:09










          • I am having erros on callback to use this.fetchPUT(this.refs.myinput.value); either to make a var/const or use text straight away can solve the issue. onMouseDown = e => { const _value = this.refs.myinput.value; this.setState( { text: _value, isEditable: false }, () => { this.fetchPUT(_value); } ); };
            – olo
            Nov 11 at 9:19

















          up vote
          2
          down vote



          accepted










          You don't have to fetch the data from backend to synchronise the value with the current text. Instead use setState callback in your onMouseDown as:



          onMouseDown = e => {
          this.setState({
          text: this.refs.myinput.value,
          }, () => {
          this.fetchPUT(this.refs.myinput.value);
          });
          };


          Here the state will be set before it makes a put call and as you're having the updated value, you don't have to fetch the value. When the component is unmounted and mounts again, it will fetch the updated value from your componentDidMount.



          Read more here



          Also



          In the render function, use onChange instead of onMouseDown (Which you're not even using) because that would be less confusing. Use debounce so that you don't have to make many API calls on every change.



          onChange = _.debounce((event) => {
          const text = event.target.value;
          this.setState({text}, () => {
          this.fetchPUT(text);
          })
          }, 500)

          render() {
          const { text } = this.state;
          return (
          <div>
          <input
          type="text"
          value={text}
          onChange={this.onChange}
          />
          </div>
          )
          }





          share|improve this answer























          • Thank you! But if I want to sync, what lifecycle method should I use?
            – olo
            Nov 11 at 9:05






          • 1




            You can use componentWillReceiveProps or componentDidUpdate. As React might deprecate componentWill* methods, you should use componentDidUpdate. You can read the documentation of React which is wonderful
            – Ajay Gaur
            Nov 11 at 9:08










          • Many thanks for you answer!
            – olo
            Nov 11 at 9:09










          • I am having erros on callback to use this.fetchPUT(this.refs.myinput.value); either to make a var/const or use text straight away can solve the issue. onMouseDown = e => { const _value = this.refs.myinput.value; this.setState( { text: _value, isEditable: false }, () => { this.fetchPUT(_value); } ); };
            – olo
            Nov 11 at 9:19















          up vote
          2
          down vote



          accepted







          up vote
          2
          down vote



          accepted






          You don't have to fetch the data from backend to synchronise the value with the current text. Instead use setState callback in your onMouseDown as:



          onMouseDown = e => {
          this.setState({
          text: this.refs.myinput.value,
          }, () => {
          this.fetchPUT(this.refs.myinput.value);
          });
          };


          Here the state will be set before it makes a put call and as you're having the updated value, you don't have to fetch the value. When the component is unmounted and mounts again, it will fetch the updated value from your componentDidMount.



          Read more here



          Also



          In the render function, use onChange instead of onMouseDown (Which you're not even using) because that would be less confusing. Use debounce so that you don't have to make many API calls on every change.



          onChange = _.debounce((event) => {
          const text = event.target.value;
          this.setState({text}, () => {
          this.fetchPUT(text);
          })
          }, 500)

          render() {
          const { text } = this.state;
          return (
          <div>
          <input
          type="text"
          value={text}
          onChange={this.onChange}
          />
          </div>
          )
          }





          share|improve this answer














          You don't have to fetch the data from backend to synchronise the value with the current text. Instead use setState callback in your onMouseDown as:



          onMouseDown = e => {
          this.setState({
          text: this.refs.myinput.value,
          }, () => {
          this.fetchPUT(this.refs.myinput.value);
          });
          };


          Here the state will be set before it makes a put call and as you're having the updated value, you don't have to fetch the value. When the component is unmounted and mounts again, it will fetch the updated value from your componentDidMount.



          Read more here



          Also



          In the render function, use onChange instead of onMouseDown (Which you're not even using) because that would be less confusing. Use debounce so that you don't have to make many API calls on every change.



          onChange = _.debounce((event) => {
          const text = event.target.value;
          this.setState({text}, () => {
          this.fetchPUT(text);
          })
          }, 500)

          render() {
          const { text } = this.state;
          return (
          <div>
          <input
          type="text"
          value={text}
          onChange={this.onChange}
          />
          </div>
          )
          }






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Nov 11 at 7:09

























          answered Nov 11 at 6:57









          Ajay Gaur

          1,85221632




          1,85221632












          • Thank you! But if I want to sync, what lifecycle method should I use?
            – olo
            Nov 11 at 9:05






          • 1




            You can use componentWillReceiveProps or componentDidUpdate. As React might deprecate componentWill* methods, you should use componentDidUpdate. You can read the documentation of React which is wonderful
            – Ajay Gaur
            Nov 11 at 9:08










          • Many thanks for you answer!
            – olo
            Nov 11 at 9:09










          • I am having erros on callback to use this.fetchPUT(this.refs.myinput.value); either to make a var/const or use text straight away can solve the issue. onMouseDown = e => { const _value = this.refs.myinput.value; this.setState( { text: _value, isEditable: false }, () => { this.fetchPUT(_value); } ); };
            – olo
            Nov 11 at 9:19




















          • Thank you! But if I want to sync, what lifecycle method should I use?
            – olo
            Nov 11 at 9:05






          • 1




            You can use componentWillReceiveProps or componentDidUpdate. As React might deprecate componentWill* methods, you should use componentDidUpdate. You can read the documentation of React which is wonderful
            – Ajay Gaur
            Nov 11 at 9:08










          • Many thanks for you answer!
            – olo
            Nov 11 at 9:09










          • I am having erros on callback to use this.fetchPUT(this.refs.myinput.value); either to make a var/const or use text straight away can solve the issue. onMouseDown = e => { const _value = this.refs.myinput.value; this.setState( { text: _value, isEditable: false }, () => { this.fetchPUT(_value); } ); };
            – olo
            Nov 11 at 9:19


















          Thank you! But if I want to sync, what lifecycle method should I use?
          – olo
          Nov 11 at 9:05




          Thank you! But if I want to sync, what lifecycle method should I use?
          – olo
          Nov 11 at 9:05




          1




          1




          You can use componentWillReceiveProps or componentDidUpdate. As React might deprecate componentWill* methods, you should use componentDidUpdate. You can read the documentation of React which is wonderful
          – Ajay Gaur
          Nov 11 at 9:08




          You can use componentWillReceiveProps or componentDidUpdate. As React might deprecate componentWill* methods, you should use componentDidUpdate. You can read the documentation of React which is wonderful
          – Ajay Gaur
          Nov 11 at 9:08












          Many thanks for you answer!
          – olo
          Nov 11 at 9:09




          Many thanks for you answer!
          – olo
          Nov 11 at 9:09












          I am having erros on callback to use this.fetchPUT(this.refs.myinput.value); either to make a var/const or use text straight away can solve the issue. onMouseDown = e => { const _value = this.refs.myinput.value; this.setState( { text: _value, isEditable: false }, () => { this.fetchPUT(_value); } ); };
          – olo
          Nov 11 at 9:19






          I am having erros on callback to use this.fetchPUT(this.refs.myinput.value); either to make a var/const or use text straight away can solve the issue. onMouseDown = e => { const _value = this.refs.myinput.value; this.setState( { text: _value, isEditable: false }, () => { this.fetchPUT(_value); } ); };
          – olo
          Nov 11 at 9:19




















          draft saved

          draft discarded




















































          Thanks for contributing an answer to Stack Overflow!


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.





          Some of your past answers have not been well-received, and you're in danger of being blocked from answering.


          Please pay close attention to the following guidance:


          • Please be sure to answer the question. Provide details and share your research!

          But avoid



          • Asking for help, clarification, or responding to other answers.

          • Making statements based on opinion; back them up with references or personal experience.


          To learn more, see our tips on writing great answers.




          draft saved


          draft discarded














          StackExchange.ready(
          function () {
          StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53246471%2freactjs-fetch-put-value-and-pass-value-to-state%23new-answer', 'question_page');
          }
          );

          Post as a guest















          Required, but never shown





















































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown

































          Required, but never shown














          Required, but never shown












          Required, but never shown







          Required, but never shown







          Popular posts from this blog

          Florida Star v. B. J. F.

          Danny Elfman

          Lugert, Oklahoma