user938363
user938363

Reputation: 10350

props assigned in constructor not available in componentDidMount

There is a component Chat defined as below:

constructor(props) {
      super(props);

      this.props = {
        eventId : props.navigation.state.params.eventId,
        user: props.navigation.state.params.user
      }
      console.log("user in chat  : ", this.props.user);
      console.log("event id in chat: ", this.props.eventId);
      this.state = {
        messages: []
      };
    };

    async componentDidMount() {
      try {
        let url = `http://192.168.2.133:3000/api/messages/e?_device_id=${encodeURIComponent(DeviceInfo.getUniqueID())}&event_id=${encodeURIComponent(this.props.eventId)}`;
        console.log("message URL : ", encodeURIComponent(url));
        let res = await fetch(encodeURIComponent(url), {
          method: "GET",
           headers: {
            "x-auth-token": "mytoken", 
          }
        });

Here is my console output:

'event id in chat: ', 1
04-08 23:42:24.456 15213 15259 E ReactNativeJS: 'Warning: %s(...): When calling super() in `%s`, make sure to pass up the same props that your component\'s constructor was passed.', 'Chat', 'Chat'
04-08 23:42:25.085 15213 15259 I ReactNativeJS: 'message URL : ', 'http%3A%2F%2F192.168.2.133%3A3000%2Fapi%2Fmessages%2Fe%3F_device_id%3D02f7e7aa907a2a2b%26event_id%3Dundefined'

There is event id equal to 1 in Chat constructor. However event_id assigned by this.props.eventId is undefined in componentDidMount. I have no clue why the this.props.eventId does not return 1 as it is in the constructor.

Here is the _onPress function in parent component which passes along 2 props:

_onPress(id) {
      this.props.navigation.navigate("Chat", {eventId: id, user: this.state.user});
    }

Upvotes: 3

Views: 68

Answers (2)

amirhosein
amirhosein

Reputation: 921

you cannot edit child props in child component, i suggest use them in state,and in componentDidMount() you can check and update that if it changes

Upvotes: 1

whd.nsr
whd.nsr

Reputation: 694

Props are immutable, you can't change them inside the component itself. Use default props instead.

Upvotes: 1

Related Questions