How to pass parameter to a onClick function in ReactJS

Viewed 53

in my application, I defined a function click_button_response(param1) which writes the param1 to a DynamoDB table.

Then my app subscribes to an IoT Topic. It will receive a real-time message from a topic. When the button is clicked, the click_button_response(param1) function, passes the url as param1. I hope url can be saved in DynamoDB. However, it gave me the error message:

"Error Error: Pass options.removeUndefinedValues=true to remove undefined values from map/array/set."

I replaced the parameter with a string and the error went away, so I am confident that I passed the parameter in a wrong way. Thank you!


import putItemInDynamoDB from functions.js

const click_button_response = async (param1) => {

  putItemInDynamoDB(param1)
}


class Sensors extends React.Component{
  constructor(props) {
    super(props);
    this.state = {
      sensorMsg: '{"null": 0}'
    };
  }

  componentDidMount(){
    Amplify.PubSub.subscribe(TOPIC).subscribe({
      next: data => {
        try{
          this.setState({ sensorMsg: data.value });
        }
        catch (error){
          console.log("Error, are you sending the correct data?");
        }
      },
      error: error => console.error(error),
      close: () => console.log('Done'),
    });
  }


  render(){
    const { sensorMsg } = this.state;
    const url = sensorMsg['param1'];
    return(
        <div className="Sensor">
          <button onClick={() => click_button_response({url})}>Button1</button>         
        </div>
    )
  }
}

1 Answers

if click_button_response expects param1 to be a string you are currently passing it an object. () => click_button_response({url}) when we enclose url in curly braces it actually gets converted into object { url: 'actual url value' }. Change the onClick handler function to this () => click_button_response(url). Also sensorMsg['param1'] is the output of this the expected url string?

Related