2

I am trying to show different html body on same tab having two buttons. I have two buttons. I want to show different html on two different buttons, for doing this i have added two functions named xyz and abc for rendering html. But I'm not getting how to call this functions. For doing this I have added one variable flag. And I am not getting how to use this flag with function xyz and abc. It should be something like if it is abc button should invoke abc function with streamLogs function and if it is xyz button it should invoke xyz function with onCloud function. This onCloud and streamLogs function contains api call of Java.

export default class ResourceLog extends React.Component{
constructor(props) {
    super(props);
    this.state = {
        streamData: {},
        streamMessage : "",
        interval : 5000,
        showDatePicker:false,
        selectionConfigs : [
            {name:"1 Hr",cssClass:"btn btn-info btn-sm",duration:300,startTime:-1,endTime:-1,diff:3600},
            {name:"3 Hr",cssClass:"btn btn-info btn-sm",duration:300,startTime:-1,endTime:-1,diff:10800},
        ],
        params : {},
        flag: true
    }
}
streamLogs = ()=> {
       if(this.props.resource.status === "ACTIVE"){
            this.setState({"streamMessage":"loading logs.."})
               axios.instance.get("api/resources/" + this.props.resource.id+"/log/stream")
               .then((resp) => {
                   this.setState({streamData : resp.data,streamMessage:""})
               }).catch(err => {       
                   this.setState({streamMessage:""})
                   NotificationManager.error("unable to fetch logs")
               })              
       }else{
            this.setState({"streamMessage":"Resource is not Active cannot fetch/stream logs..."})              
       }
}
onCloud = () =>{

    let endTime = this.state.params.endTime;
    if(endTime === -1){
        endTime = new Date().getTime();
    }
    let startTime = this.state.params.startTime;
    if(startTime === -1){
        startTime = endTime - this.state.params.diff*1000;
    }

    let filter = this.state.params.duration;
    if(filter === -1){
        filter = "";
    }

    let params = Object.assign({},{startTime:startTime,endTime:endTime,filter:period});

    this.setState({"streamMessage":"loading stats.."});
       axios.instance.get("api/resources/" + this.props.resource.id+"/cloud/log",{params:params})
       .then((resp) => {               
           this.setState({data : resp.data,streamMessage:""})
       }).catch((error) => {
            NotificationManager.error(`Failed to fetch stats-`, "Error")
          })
}
onChange = () => {
    const flag = this.state.flag;
    let button;

    if (flag) {
        button = <abc onClick={this.streamLogs} />;
    } else {
        button = <xyz onClick={this.onCloud} />;
    }
}
render(){   
    return (
        <div>
            <button onClick={this.streamLogs}>abc</button>
            <button onClick={this.onCloud}>xyz</button>
        </div>
    )
}
abc = () =>{
    return (
            <div className="row"  style={{"margin":"15px"}}>
                <div className="col-md-12">
                    <h3 style={{display:"inline"}}>Logs
                        <span style={{marginLeft:"10px", cursor:"pointer"}} title={"Download"}><a target="_blank" href={`api/resources/${this.props.resource.id}/log`}><i className="fa fa-download"></i></a></span>
                        <span style={{marginLeft:"10px", cursor:"pointer"}} title={"Refresh"}><i onClick={this.streamLogs} className="fa fa-refresh"></i></span>
                    </h3>
                </div>
                <div className="clearfix"/>
                <br />
                <div className="col-md-12">
                    <div>{this.state.streamMessage}</div>
                    {mapObject(this.state.streamData,(k,v) => <div><pre>{v.join("\n")}</pre></div>)}
                </div>
            </div>
    );
}
xyz = () =>{
    return(
        <div className="row" style={{margin:"20px",textAlign:"center"}}>
            <div>
                <span className={this.state.selectionConfigs[0].cssClass} onClick={() =>this.updateStatsConf(this.state.selectionConfigs[0])}>{this.state.selectionConfigs[0].name}</span>
                <span style={{marginLeft:"10px"}} className={this.state.selectionConfigs[1].cssClass} onClick={() =>this.updateStatsConf(this.state.selectionConfigs[1])}>{this.state.selectionConfigs[1].name}</span>
                <span style={{marginLeft:"10px"}} className={this.state.selectionConfigs[2].cssClass} onClick={() =>this.updateStatsConf(this.state.selectionConfigs[2])}>{this.state.selectionConfigs[2].name}</span>
            </div>

        <div className="row" style={{margin:"20px"}}>
            <div className="col-md-12">
                    <div>{this.state.streamMessage}</div>
                    {mapObject(this.state.streamData,(k,v) => <div><pre>{v.join("\n")}</pre></div>)}
            </div>
        </div>
    </div>

    );
}

}

1 Answer 1

1

Please find the best approach to handle for any number of buttons. I commented come unwanted methods too.

export default class ResourceLog extends React.Component{
constructor(props) {
    super(props);
    this.state = {
        streamData: {},
        streamMessage : "",
        interval : 5000,
        showDatePicker:false,
        selectionConfigs : [
            {name:"1 Hr",cssClass:"btn btn-info btn-sm",duration:300,startTime:-1,endTime:-1,diff:3600},
            {name:"3 Hr",cssClass:"btn btn-info btn-sm",duration:300,startTime:-1,endTime:-1,diff:10800},
        ],
        params : {},
        flag: true
    }
}
streamLogs = ()=> {
       if(this.props.resource.status === "ACTIVE"){
            this.setState({"streamMessage":"loading logs.."})
               axios.instance.get("api/resources/" + this.props.resource.id+"/log/stream")
               .then((resp) => {
                   this.setState({streamData : resp.data,streamMessage:"", show: "abc"})
               }).catch(err => {       
                   this.setState({streamMessage:""})
                   NotificationManager.error("unable to fetch logs")
               })              
       }else{
            this.setState({"streamMessage":"Resource is not Active cannot fetch/stream logs..."})              
       }
}
onCloud = () =>{

    let endTime = this.state.params.endTime;
    if(endTime === -1){
        endTime = new Date().getTime();
    }
    let startTime = this.state.params.startTime;
    if(startTime === -1){
        startTime = endTime - this.state.params.diff*1000;
    }

    let filter = this.state.params.duration;
    if(filter === -1){
        filter = "";
    }

    let params = Object.assign({},{startTime:startTime,endTime:endTime,filter:period});

    this.setState({"streamMessage":"loading stats.."});
       axios.instance.get("api/resources/" + this.props.resource.id+"/cloud/log",{params:params})
       .then((resp) => {               
           this.setState({data : resp.data,streamMessage:"", show: "abc"})
       }).catch((error) => {
            NotificationManager.error(`Failed to fetch stats-`, "Error")
          })
}
// onChange = () => {
//     const flag = this.state.flag;
//     let button;

//     if (flag) {
//         button = <abc onClick={this.streamLogs} />;
//     } else {
//         button = <xyz onClick={this.onCloud} />;
//     }
// }
getBody = () => {
    if(this.state.show == "abc"){
        return (
            <div className="row"  style={{"margin":"15px"}}>
                <div className="col-md-12">
                    <h3 style={{display:"inline"}}>Logs
                        <span style={{marginLeft:"10px", cursor:"pointer"}} title={"Download"}><a target="_blank" href={`api/resources/${this.props.resource.id}/log`}><i className="fa fa-download"></i></a></span>
                        <span style={{marginLeft:"10px", cursor:"pointer"}} title={"Refresh"}><i onClick={this.streamLogs} className="fa fa-refresh"></i></span>
                    </h3>
                </div>
                <div className="clearfix"/>
                <br />
                <div className="col-md-12">
                    <div>{this.state.streamMessage}</div>
                    {mapObject(this.state.streamData,(k,v) => <div><pre>{v.join("\n")}</pre></div>)}
                </div>
            </div>
        );
    }else if(this.state.show == "xyz"){
        return(
            <div className="row" style={{margin:"20px",textAlign:"center"}}>
                <div>
                    <span className={this.state.selectionConfigs[0].cssClass} onClick={() =>this.updateStatsConf(this.state.selectionConfigs[0])}>{this.state.selectionConfigs[0].name}</span>
                    <span style={{marginLeft:"10px"}} className={this.state.selectionConfigs[1].cssClass} onClick={() =>this.updateStatsConf(this.state.selectionConfigs[1])}>{this.state.selectionConfigs[1].name}</span>
                    <span style={{marginLeft:"10px"}} className={this.state.selectionConfigs[2].cssClass} onClick={() =>this.updateStatsConf(this.state.selectionConfigs[2])}>{this.state.selectionConfigs[2].name}</span>
                </div>

            <div className="row" style={{margin:"20px"}}>
                <div className="col-md-12">
                        <div>{this.state.streamMessage}</div>
                        {mapObject(this.state.streamData,(k,v) => <div><pre>{v.join("\n")}</pre></div>)}
                </div>
            </div>
        </div>

        );
    }else{
        <h1> please click a BUtton </h1>
    }
}
render(){   
    return (
        <div>
            <button onClick={this.streamLogs}>abc</button>
            <button onClick={this.onCloud}>xyz</button>
            {this.getBody()}
        </div>
    )
}
    // abc = () =>{

    // }
    // xyz = () =>{

    // }
}

So every time after you fetch the data successfully you trigger a state show which has what to show in the body check getBody() method for all the view handling. even the source looks well organised.

Sign up to request clarification or add additional context in comments.

2 Comments

This looks good but i'm not getting output, this.state.show is not defined
intially i havent set it to any state . instead asking to select any button. thought that was the useCase :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.