#StackBounty: #javascript #reactjs getDerivedStateFromProps, change of state under the influence of changing props

Bounty: 50

I click Item -> I get data from url:https: // app / api / v1 / asset / $ {id}. The data is saved in loadItemId. I am moving loadItemId from the component Items to the component Details, then to the component AnotherItem.
Each time I click Item the props loadItemId changes in the getDerivedStateFromProps method. Problem: I’ll click Element D -> I see in console.log ‘true’, then I’ll click Element E –> It display in console.log true andfalse simultaneously, and it should display only false.

Trying to create a ternary operator {this.state.itemX ['completed'] ? this.start () : ''}. If {this.state.itemX ['completed'] call the function this.start ()

Code here: stackblitz

Picture: https://imgur.com/a/OBxMKCd

Items

class Items extends Component {
  constructor (props) {
    super(props);
    this.state = {   
      itemId: null,  
      loadItemId: ''
    }
  }

  selectItem = (id) => {
    this.setState({
      itemId: id
    })

        this.load(id);
  }

    load = (id) => {

        axios.get
            axios({
                    url: `https://app/api/v1/asset/${id}`,
                    method: "GET",
                    headers: {
                        'Authorization': `Bearer ${token}`           
                    }
            })
            .then(response => {
                    this.setState({
                            loadItemId: response.data
                    });
            })
            .catch(error => {
                    console.log(error);
            })
}

  render () {
    return (
            
) }

Item

class Item extends Component {
  render () {

    return (
      
this.props.selectItem(item.id}>
) } }

Details

class Details extends Component {
    constructor() {
        super();
    }

  render () {
    return (
            
) } }

AnotherItem

class AnotherItem extends Component {


  constructor() {
    super();

    this.state = {
      itemX: ''
    };
  }


  static getDerivedStateFromProps(nextProps, prevState) {
    if(nextProps.loadItemId !== prevState.loadItemId) {
      return { itemX: nextProps.loadItemId }
    }

  render () {
      console.log(this.state.itemX ? this.state.itemX['completed'] : '');

    {/*if this.state.loadX['completed'] === true, call function this.start()*/ }
    return (
            <button /*{this.state.loadX['completed'] ? this.start() : ''}*/ onClick={this.start}>
                Start
            </button>      
    );
  }
}


Get this bounty!!!

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.