Chen
Chen

Reputation: 291

why is props only working in render function?

I have the following code inside render and when I console log it, the correct values appear:

    render() {
        const { total } = this.state;      
        const filter = this.props.catalog.filter(word => word.markets.some(m => m === this.props.currentMarket))
        
        console.log(filter)
        console.log(this.state.filtered)
}

But when I do the same for a componentDidMount() hook it doesn't work.

export class Products extends React.Component {
  constructor(props){
    super(props)
      this.state = {
        filtered: []
      };
    }


  componentDidMount() {
        console.log(this.props.catalog.filter(word => word.markets.some(m => m === this.props.currentMarket)))

    const filter = this.props.catalog.filter(word => word.markets.some(m => m === this.props.currentMarket))
    this.setState({
      filtered: filter
    })
  }
  

  renderProductCards() {
    return <ProductCard product={this.props?.catalog}/>
  }

  render() {
    const { total } = this.state;      
    const filter = this.props.catalog.filter(word => word.markets.some(m => m === this.props.currentMarket))
    console.log(filter)
    console.log(this.state.filtered)
    return (
      <div>
        <div className="ui divider"></div>
      </div>
    );
  }
}

So for the first render hook I get the correct values of the filter but for componentDidMount() I get nothing as the value, I get the state value but it doesn't setState correctly and when I console log it it appears nothing.

Upvotes: 0

Views: 67

Answers (2)

Nice Books
Nice Books

Reputation: 1861

When updating state using previous state or props, the callback argument should be used.
See https://reactjs.org/docs/state-and-lifecycle.html#state-updates-may-be-asynchronous

It should be

componentDidMount() {
    this.setState((state, props)=> ({
        filtered: props.catalog.filter((word)=>(
            word.markets.some(m => m == props.currentMarket)
        ))   
    }));
}

Upvotes: 1

Hossein hossein
Hossein hossein

Reputation: 147

I assume that you didn't call super(props) in your constructor. Try this:

constructor(props){
  super(props); // Add this line to constructor
  this.state = {
     //states
  };
}

Upvotes: 0

Related Questions