program_bumble_bee
program_bumble_bee

Reputation: 305

passing multiple functions inside main function

I am trying to achieve a workaround which calls two functions inside a main function on the basis of if condition. The main function is toggled onClick/onChange event handler.

fetchData = command => e => {
    if (e.target.tagName === "BUTTON") {
      console.log("Button Clicked!");

      this.setState({
        command
      });

      this.ButtonData = command => {
        console.log(command, "command received");
      };
    } else if (e.target.tagName === "INPUT") {
      console.log("Input Clicked!");

      this.setState({
        command
      });

      this.InputData = command => {
        console.log(command, "command received");
      };
    }
  };

The code only works till first console printing, 'clicked' but then doesn't follow inside the function called in if condition.

Here is the working sandbox: https://codesandbox.io/embed/pensive-bash-fmmmd

Please help to achieve the same.

Upvotes: 0

Views: 147

Answers (1)

Mosè Raguzzini
Mosè Raguzzini

Reputation: 15861

This is the correct way, try to paste it in your example:

import React, { Component } from "react";

export default class extends Component {
  constructor() {
    super();

    this.state = {
      command: "",
      text_start: "enter text one",
      text_end: "enter text two"
    };
  }

  componentDidMount() {
    this.fetchData();
  }

  buttonData = command => {
  console.log(command, "command received");
  };

  inputData = command => {
    console.log(command, "command received");
  };

  fetchData = command => e => {
    if (e.target.tagName === "BUTTON") {
      console.log("Button Clicked!");

      this.setState({
        command
      });

      this.buttonData(command);
    } else if (e.target.tagName === "INPUT") {
      console.log("Input Clicked!");

      this.setState({
        command
      });

      this.inputData(command);
    }
  };
  render() {
    return (
      <>
        <div>
          <button value="start" onClick={this.fetchData("start")}>
            Start
          </button>
          <button value="stop" onClick={this.fetchData("stop")}>
            Stop
          </button>
        </div>

        <div>
          <input
            type="text"
            name="start"
            value={this.state.text_start}
            onChange={this.fetchData("e")}
          />

          <input
            type="text"
            name="end"
            value={this.state.text_end}
            onChange={this.fetchData("e")}
          />
        </div>
      </>
    );
  }
}

Upvotes: 2

Related Questions