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>
);
}
}
CodePudding user response:
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)
}