0

I am just starting to learn reactjs and one of my first use cases is creating a button where depending if user clicks on/off I will make a fetch call and pass this information into one of the variables.I want to eliminate having a function for each type of button. So I figured I could just pass in the value as a prop and use that for the fetch call. You will see this when I try to pass in "this.props.statusnumber".

Unfortunately I get the following error; Parsing error: this is a reserved word...

Here is my code, any help would be greatly appreciated since I cant find anything online.

import React from 'react';


const API = 'https://use1-wap.tplinkcloud.com/?token=HIDDEN';
let opts = {"method":"passthrough", "set_dev_alias":{"alias":"supercool             plug"}, "params": {"deviceId": "HIDDEN", "requestData": "{\"system\":    {\"set_relay_state\":{\"state\":0}}}" }};
let headerInfo = {'Content-Type': 'application/json','Version':'1','q': '0.01'};
let statusnumber = {};

export class Name extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      position: "off",
      object: [],
    };
    this.switchStatus = this.switchStatus.bind(this);
    this.statusnumber = this.statusnumber.bind(this);
  }

  switchStatus() {
    opts.params.requestData = "{\"system\":{\"set_relay_state\ {\"state\":"+{this.props.statusnumber}+"}}}";
    let positionStatus = (this.props.statusnumber === 0) ? "off" : "on";
    console.log(this.props.statusnumber);
    fetch(API, {
        method : 'POST',
        headers: headerInfo,
        body : JSON.stringify(opts)
    })
      .then(response => response.json())
      .then(data => this.setState({ object: data.object, position:     positionStatus}))
  };


  render() {
    const { object } = this.state;

    return (

      <div>
      <button onClick={this.switchStatus} statusnumber={1}>On</button>
      <button onClick={this.switchStatus} statusnumber={0}>Off</button>
      <p>Current position: {this.state.position}</p>
      <p>testing function</p>
      </div>
    );
  }

}
Jose
  • 15
  • 1
  • 7
  • 1
    You have a misleading understanding of what `props` are in React. Have a look [at the official docs first](https://reactjs.org/docs/components-and-props.html). – c-chavez Nov 07 '18 at 07:52
  • You want to pass a `parameter` to the function, not a `prop`. Have a look at [this](https://stackoverflow.com/questions/29810914/react-js-onclick-cant-pass-value-to-method) to help you. Also, since you are starting with React, I suggest you switch to Axios instead of fetch, have a look at [the differences between axios and fetch](https://stackoverflow.com/a/50326744/1042409) – c-chavez Nov 07 '18 at 07:58

0 Answers0