mwd1990
mwd1990

Reputation: 55

Updating State after Patch in React

I am trying to figure out how to automatically update the state after a patch request so when one clicks the button, it will automatically add their like within the counter. Unfortunately, it still takes a page load to update. Is there anything you may be seeing on this? Any help greatly appreciated thank you.

import React, { Component } from "react";
import "./Like.css";

class Button extends Component {
  constructor(props) {
    super(props);
    this.state = {
      counter: this.props.counter
    };
  }

  handleSubmit = event => {
    event.preventDefault();
    fetch(`http://localhost:3001/api/tracklists/${this.props.id}`, {
      method: "PATCH",
      headers: {
        Accept: "application/json",
        "Content-Type": "application/json"
      },
      body: JSON.stringify({
        tracklist: {
          title: this.props.title,
          url: this.props.url,
          genre: this.props.genre,
          tracklist: this.props.tracklist,
          likes: this.props.counter + 1
        }
      })
    })
      .then(response => response.json())
      .then(response => {
        this.setState({
          counter: this.props.counter
        });
      });
  };

  render() {
    return (
      <div className="customContainer">
        <button onClick={this.handleSubmit}>{this.state.counter}</button>
      </div>
    );
  }
}

export default Button;

Upvotes: 0

Views: 4684

Answers (1)

Rom
Rom

Reputation: 426

Welcome to SO

I don't see your props declared anywhere but I assume it is for space saving and readability purposes.

Have you tried using React Component's built-in lifecycle method componentDidUpdate(prevProps)?

In your case you would do

componentDidUpdate(prevProps) {
  // you always need to check if the props are different
  if (this.props.counter !== prevProps.counter) {
    this.setState({ counter: this.props.counter });
  }
}

You can find the documentation here: https://reactjs.org/docs/react-component.html#componentdidupdate

That being said, I do not see why you wouldn't display the prop directly instead of duplicating it in a state... As in:

render() {
  return (
    <div className="customContainer">
      <button onClick={this.handleSubmit}>{this.props.counter}</button>
    </div>
  );
}

Upvotes: 1

Related Questions