yasin demir
yasin demir

Reputation: 135

react-native-navigation get params in componentDidMount

i'm trying to list some products. i want to get categoryName as title by navigation, well if i put that line in render it works but i need to use it in componentDidMount how can i do that? is there any suggestions?

there is some part of my code

export default class ProductList extends React.Component {
  navigation = this.props.navigation;
  constructor(props) {
    super(props);
    this.state = {
      isData: false,
    };
  }
  componentDidMount() {
    const title = navigation.route.params.categoryName;  //here is my problem
    fetch(global.apiPost + global.token, requestOptions)
      .then((response) => response.json())
      .then((result) => {
        result.forEach((element) => {
          if (element.Menu === title) {
            products.push(element);
          }
        });
        this.setState({isData: true});
      })
      .catch((error) => console.log('error', error));
  }

Upvotes: 1

Views: 360

Answers (1)

Nikhil bhatia
Nikhil bhatia

Reputation: 1397

put a check in componentDidMount

componentDidMount() {
if (navigation?.route?.params?.categoryName){
 const title = navigation.route.params.categoryName;  //here is my problem
fetch(global.apiPost + global.token, requestOptions)
  .then((response) => response.json())
  .then((result) => {
    result.forEach((element) => {
      if (element.Menu === title) {
        products.push(element);
      }
    });
    this.setState({isData: true});
  })
  .catch((error) => console.log('error', error));
}

}

Upvotes: 1

Related Questions