Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to call function from function array (React js)

I Created array that contains functions and now I am trying to call a function from that array, I tried this code but it’s not working and I have no idea how can I do it becuase I am pretty new at react js. Can someone help me with this?

here is my code

import React, { Component } from "react";
import "../App.css";

export default class Chart extends Component {
  constructor(props) {
    super(props);
    this.state = {
      stockChartXValues: "",
      stockChartYValues: "",
      type: props.data,
    };
  }

  getBTC = () => {
    // .....
  };

  getETH = () => {
    // .....
  };

  getADA = () => {
    // .....
  };

  componentDidMount() {
    // here I am trying to run a function according to the "type" variable
    var options = ["BTC", "ETH", "ADA"];
    var functions = [this.getBTC, this.getETH, this.getADA];
    var func = functions.indexOf(options.indexOf(this.state.type));
    func.call();
  }

  render() {
    return (
      <div>
        <h1>Hello world</h1>
      </div>
    );
  }
}

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

you need to get function with the index you found;

  var func = functions.indexOf(options.indexOf(this.state.type));// this returns index not the actual func
  functions[func] && functions[func]()

My Approach would be like;

  getBTC = () => {
    // .....
  };

  getETH = () => {
    // .....
  };

  getADA = () => {
    // .....
  };

  getCoin = (type) => {
    switch(type) {
    case "BTC": this.getBTC()
      return
    case "ADA":...
    ...
    ...
    }

  componentDidMount() {
    this.getCoin(this.state.type)
  }
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading