React: call setState from another component

Viewed 11716

This is the parent component:

class Parent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      news: ""
    }
  }
  componentDidMount() {
    this.updateNews();
  }

  updateNews = () => {
      ...
  }

  render() {
      <CustomButton type="primary"  />
  }

This is the CustomButton:

const CustomButton = (props) => {
  const {
    type
  } = props;


  const updateItem = () => {
     ... // The firing of the setState should be here
  }

  return (
   <Button
    type={type}
    onClick={() => {
        updateItem();
      }}
    >{value}
   </Button>
  );

How can I fire from inside const updateItem = () => { in CustomButton, so that Parent runs updateNews or componentDidMount?

2 Answers

Use the componentDidUpdate in Parent component like this.

class Parent extends Component {
  constructor(props) {
   super(props);
   this.state = {
    news: "",
    fetchToggle:true
   }
  }
  componentDidMount() {
   this.updateNews();
  }

  componentDidUpdate(prevprops,prevstate){
    if(prevstate.fetchToggle!==this.state.fetchToggle){
       this.updateNews();
    }
  }
  updateNews = () => {
   ...
  }
  fetchToggle=()=>{
     this.setState({
      fetchToggle:!this.state.fetchToggle;
     })
   }

  render() {
    <CustomButton type="primary" fetchToggle={this.fetchToggle} />
  }

In the child component clicking on button call this toggle function.

const CustomButton = (props) => {
  const {
   type
  } = props;

  const updateItem = () => {
   ... // The firing of the setState should be here
  } 

  return (
   <Button
     type={type}
     onClick={() => {
       props.fetchToggle()
     }}
   >{value}
   </Button>
  );

Remember that a toggling value in state is a cleaner and elegant way to update or fetch latest data on every click.

You should pass a callback function to the CustomButton, something like that:

class Parent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      news: ""
    }
  }
  componentDidMount() {
    this.updateNews();
  }

  updateNews = () => {
      ...
  }

  render() {
      <CustomButton type="primary"  stateUpdatingCallback={(val) => {this.setState({myVal: val})}}/>
  }


const CustomButton = (props) => {
  const {
    type
  } = props;


  const updateItem = () => {
     ... // The firing of the setState should be here
  }

  return (
   <Button
    type={type}
    onClick={() => {
        this.props.stateUpdatingCallback("somevalue")
      }}
    >{value}
   </Button>
);
Related