0

i'm doing some graphs work and when i change the graph instead of trying to look for all variables in the screen to zero and to look at all the graphs functions to render it live i just want to restart the current screen (meaning as if it would go to the same scene for the first time)

how do i do that without actually exiting and reentering the scene ?

to be sure here is my code:

import React, {Component} from 'react';
import {View, Text, StyleSheet, processColor, Picker} from 'react-native';
import { Button} from "native-base";
import './globals.js'


import {CombinedChart} from 'react-native-charts-wrapper';
import moment from 'moment';

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'center',
        alignItems: 'stretch',
        backgroundColor: 'transparent',
        paddingTop:20
    }
});

var InsulinShort = [];
var InsulinLong = [];
var glocuseTests = [];
const injectionsCount = 1000;

for (var i = 1; i < injectionsCount; i++) {
    var random = Math.random();
    if (random <= 0.7) {
        var gloguseValue = Math.floor(Math.random() * 40) + 75;
        var gloguseposition = Math.random();

        glocuseTests.push({x:i+gloguseposition, y: gloguseValue, marker: "level: "+gloguseValue});

    }
}
for (var i = 1; i < injectionsCount; i++) {
    var random = Math.random();
    if (random <= 0.15) {
        var shortvalue = Math.floor(Math.random() * 16) + 1  ;
        var shortPosition = Math.round(Math.random() * 100) / 100;
        InsulinShort.push({x:i+shortPosition,y: shortvalue*20, marker: shortvalue+ " units of short insulin"});
    }else if (random <= 0.3) {
        var longePosition = Math.round(Math.random() * 10) / 10;
        var longvalue = Math.floor(Math.random() * 16) + 1;
        InsulinLong.push({x:i+longePosition,y: longvalue*20, marker: longvalue+ " units of long insulin"});
    }else{
    }
}
export default class LogGraph extends Component {

    constructor() {
        super();
        // var valueFormatter = new Array(3515599953920);


        this.state = {
            selectedPeriod: "all",
            loading: true,
            days:365,
            legend: {
                enabled: true,
                textSize: 18,
                form: 'SQUARE',
                formSize: 18,
                xEntrySpace: 10,
                yEntrySpace: 5,
                formToTextSpace: 5,
                wordWrapEnabled: true,
                maxSizePercent: 0.5
            },
            xAxis: {
                valueFormatter: [
                    '01/04/18',
                    '02/04/18',
                    '03/04/18',
                    '04/04/18',
                    '05/04/18',
                    '06/04/18',
                    '07/04/18',
                    '08/04/18',
                    '09/04/18',
                    '10/04/18',
                    '11/04/18',
                    '12/04/18',
                    '13/04/18',
                    '14/04/18',
                    '15/04/18',
                    '16/04/18',
                    '17/04/18',
                    '18/04/18',
                    '19/04/18',
                    '20/04/18',
                ],
                // valueFormatterPattern:'ssss',
                // limitLines:100,
                // drawLimitLinesBehindData:false,
                // avoidFirstLastClipping: false,
                textColor: processColor('#000'),
                gridColor: processColor('#000'),
                axisLineColor: processColor('#000'),
                drawGridLines:true,
                drawAxisLine:false,
                drawLabels:true,

                granularityEnabled: true,
                // granularity:1515599953920,
                granularity: 1,
                // granularity: 131096  ,
                position:'TOP',
                textSize: 10,
                labelRotationAngle:45,
                gridLineWidth: 1,
                axisLineWidth: 2,
                gridDashedLine: {
                    lineLength: 10,
                    spaceLength: 10
                },
                centerAxisLabels:false,
            },

            yAxis: {
                left: {
                    axisMinimum: 0,
                    axisMaximum: 400,
                    labelCount: 6,
                    labelCountForce: true,
                    granularityEnabled: true,
                    granularity: 5,
                },
                right: {
                    axisMinimum: 0,
                    axisMaximum: 20,
                    labelCount: 6, // 0 5 10 15 20 25 30
                    labelCountForce: true,
                    granularityEnabled: true,
                    granularity: 5,
                }
            },

            marker: {
                enabled: true,
                markerColor: processColor('#F0C0FF8C'),
                textColor: processColor('white'),
                markerFontSize: 18,
            },

            data: {
                barData: {
                    config: {
                        barWidth: 1 / 24 ,
                    },
                    dataSets: [{
                        values:InsulinLong,
                        label: 'Long Insulin',
                        config: {
                            drawValues: false,
                            colors: [processColor('#a2a4b2')],
                        }
                    },{
                        values:InsulinShort,
                        label: 'Short Insulin',
                        config: {
                            barShadowColor: processColor('red'),
                            highlightAlpha: 200,
                            drawValues: false,
                            colors: [processColor('#d0d5de')],
                        }
                    }]

                },
                lineData: {
                    dataSets: [{
                        values: glocuseTests,
                        label: 'Glucose Level',
                        config: {
                            drawValues: false,
                            colors: [processColor('#0090ff')],
                            // mode: "CUBIC_BEZIER",
                            drawCircles: true,
                            lineWidth: 3,
                        }
                    }],
                },
            }
        };

    }


    pickerZoomSelected (value) {
      // this.setState({selectedPeriod: value})
      global.graphStateChoosen = value
      this.resetscreen();

    }

    resetscreen() {

    }


    pickerDaysSelected (value) {
      this.setState({days: value})
    }

    isGraphItemLegal (itemTime) {

      // console.log ("log was made at: "+itemTime)

      // multiplied by 1000 so that the argument is in milliseconds, not seconds.
      var itemDate = new Date(itemTime*1000);
      // Hours part from the timestamp
      var itemHour = itemDate.getHours();
      // Minutes part from the timestamp
      var itemMinutes = "0" + itemDate.getMinutes();
      // Seconds part from the timestamp
      var itemSeconds = "0" + itemDate.getSeconds();

      // console.log ("refactured: "+itemHour + ':' + itemMinutes.substr(-2) + ':' + itemSeconds.substr(-2));
      // console.log ("selected piriod: " + this.state.selectedPeriod);

      if (global.graphStateChoosen == "all")  {
        // console.log ("dont show item+1");
        return true;
      }

      // //blocks morning \ afternoon \ evening
      if ((itemHour > 18) && (itemHour < 24)) {
        console.log ("EVENING ITEM: "+itemHour + ':' + itemMinutes.substr(-2) + ':' + itemSeconds.substr(-2));
        // console.log ("is it equal ?: " + this.state.selectedPeriod == "evening");

        if (!(global.graphStateChoosen == "evening")|| (global.graphStateChoosen == "all"))  {
          // console.log ("dont show item+1");
          return false;
        }

      } else if ((itemHour > 6) && (itemHour < 13)) {
        console.log ("MORNING ITEM: "+itemHour + ':' + itemMinutes.substr(-2) + ':' + itemSeconds.substr(-2));
        // console.log ("is it equal ?: " + this.state.selectedPeriod == "evening");
        if (!(global.graphStateChoosen === "morning")|| (global.graphStateChoosen == "all"))  {
          // console.log ("dont show item+2");
          return false;
        }

      } else if ((itemHour > 13) && (itemHour < 18)) {
        console.log ("AFTERNOON ITEM: "+itemHour + ':' + itemMinutes.substr(-2) + ':' + itemSeconds.substr(-2));
        if (! (global.graphStateChoosen == "afternoon") || (global.graphStateChoosen == "all"))  {
          // console.log ("dont show item+3");
          return false;
        }
      }

      return true;

    }

    clearList() {

    }

    creatList(logs){
        // var startTime = moment().millisecond();

        var list = [];

        var time = false;

        if (logs) {
            // console.log('firstLogDay',moment(firstLogDay).format('L'));
            let gloguseItems   = [];
            let shortItems     = [];
            let longItems      = [];
            let firstValidFlag = false;
            let firstLogTime;
            let lastLogTime;
            let days;
            let firstLogDate;
            let firstLogDayTime;
            lastLogTime        = logs[0].time;
            for (var i = logs.length-1; i >= 0; i--) {
                console.log ("cheking i: "+i);
                let item = logs[i];
                if ( !firstValidFlag &&  ['glucose', 'long', 'short'].indexOf(item.type) >= 0 )  {
                    // debugger;
                    firstValidFlag = true;
                    firstLogTime = logs[i].time;
                    days = Math.round((lastLogTime-firstLogTime)/(1000*60*60*24));
                    firstLogDate = moment(firstLogTime).format('YYYY-MM-DD');
                    // console.log('firstLogDate',firstLogDate);
                    firstLogDayTime = new Date(firstLogDate);
                    firstLogDayTime = firstLogDayTime.getTime() - (2*60*60*1000);
                    // console.log('firstLogDayTime',firstLogDayTime);
                }

                console.log ("runing on i: "+i);
                console.log ("with our time: "+this.state.graphStateChoosen);

                var isItemLegal = this.isGraphItemLegal(item.time);

                console.log ("answer is: " + isItemLegal);

                if ((firstValidFlag) && (isItemLegal)) {

                    let logX = ( item.time - firstLogDayTime ) /  1000 / 60 / 60 /24;

                    // logX =  Math.round(logX * 10) / 10
                    if (logX) {
                        // logX = item.time;
                        // console.log(logX);
                        let logY = item.amount;
                        if (item.type !== 'glucose') {
                            if (item.type === 'short') {
                                shortItems.push({
                                    x: logX,
                                    y:  logY*20,
                                    marker: logY+ " units of short insulin" + moment(item.time).format('LLL')
                                })
                            }
                            if (item.type === 'long') {
                                longItems.push({
                                    x: logX,
                                    y:  logY*20,
                                    marker: logY+ " units of long insulin" +  moment(item.time).format('LLL')
                                })
                            }
                        }else{
                            if(item.type === 'glucose'){
                                gloguseItems.push({
                                    x: logX,
                                    y: parseInt(logY),
                                    marker: "level: "+ logY +  moment(item.time).format('LLL')
                                })
                            }
                        }
                    }
                }

            }

            console.log ("Reached Here");

            let oldData = this.state.data;

            console.log ("Reached Here 1");
            oldData.lineData.dataSets[0].values = gloguseItems;
            oldData.barData.dataSets[1].values = shortItems;
            oldData.barData.dataSets[0].values = longItems;


            let DayFlag = firstLogDate;
            let valueFormatter = [];

            console.log ("Reached Here 2");
            valueFormatter.push(moment(DayFlag).format('DD/MM/YYYY'));
            for (let i = 0; i < days; i++) {
                DayFlag = moment(DayFlag).add(1, 'days');
                valueFormatter.push(DayFlag.format('DD/MM/YYYY'));
            }

            console.log ("Reached Here 3");
            let xAxis = this.state.xAxis;
            xAxis.valueFormatter = valueFormatter;
            console.log ("Reached Here 4");
            this.setState({
                data:oldData,
                days:days,
                xAxis:xAxis,
                loading:false
            });

            console.log ("Reached Here 5");

        }else{
            this.setState({loading:false});
        }

    }

    componentDidMount() {

        this.creatList(this.props.logs);
    }

    zoomTwentyPressed() {
      console.log ("pressed 25");
    }

    zoomFiftyPressed() {
      console.log ("pressed 50");
    }

    zoomHundredPressed() {
      console.log ("pressed 100"+this.state.days);
      // CHANGE ZOOM HERE
      // this.combinedChart.zoom = 80
      // this.setState({days: this.state.days/2})

    }


    static displayName = 'Combined';

    handleSelect(event) {
        let entry = event.nativeEvent
        if (entry == null) {
            this.setState({...this.state, selectedEntry: null})
        } else {
            this.setState({...this.state, selectedEntry: JSON.stringify(entry)})
        }

        // console.log(event.nativeEvent)
    }

    render() {
        return (

            <View style={styles.container}>

                {
                    (this.state.loading) ? <Text>Loading</Text>:
                    <CombinedChart
                        data={this.state.data}
                        ref={component => this.combinedChart = component}
                        xAxis={this.state.xAxis}
                        yAxis={this.state.yAxis}
                        legend={this.state.legend}
                        onSelect={this.handleSelect.bind(this)}
                        onChange={(event) => console.log(event.nativeEvent)}
                        marker={this.state.marker}
                        animation={{durationY: 1000,durationX: 1000}}
                        maxVisibleValueCount={16}
                        autoScaleMinMaxEnabled={true}
                        zoom={{scaleX: Math.floor(this.state.days/12), scaleY: 1, xValue:  4, yValue: 4, axisDependency: 'LEFT'}}
                        style={styles.container}/>
                }

                <Text style={{
                  paddingLeft: 20,
                  fontSize: 20
                }}>
                  Zoom Options
                </Text>

                <View style={styles.buttonWrap}>

                    <View style={{
                      flexDirection:'row',
                      marginLeft:20,
                      paddingLeft: 80,
                      paddingTop: 20,
                      justifyContent: 'space-around',
                    }}>


                    <Picker
                      style={{width:'80%'}}
                      selectedValue={this.state.PickerValueLong}
                      onValueChange={ (itemValue, itemIndex) => {
                          // console.log(this);
                          this.pickerDaysSelected(itemValue);
                        }}>

                      <Picker.Item label="x100 Days" value='100' />
                      <Picker.Item label="x50 Days" value='50' />
                      <Picker.Item label="x25 Days" value='25' />

                    </Picker>


                    <Picker
                      style={{width:'80%'}}
                      selectedValue= {global.graphStateChoosen}
                      onValueChange= {(itemValue, itemIndex) => {
                          // console.log(this);
                          this.pickerZoomSelected(itemValue);
                        }}>

                      <Picker.Item label="Morning" value='morning' />
                      <Picker.Item label="Afternoon" value='afternoon' />
                      <Picker.Item label="Evening" value='evening' />
                      <Picker.Item label="All Day" value='all' />

                    </Picker>




                    </View>



                </View>

            </View>


        );

    }
}

thnx

Chief Madog
  • 1,738
  • 4
  • 28
  • 55

2 Answers2

1

It's not something you usually do from inside that screen. But on it's container, you could render a null and the scene back again.

Bruno Reis
  • 326
  • 2
  • 7
  • what function would you call though from the scene button listener ? – Chief Madog May 29 '18 at 09:54
  • I would rather inject a callback from it's container that would change that on the container level. Let's say... set a isVisible state (on it's container) to false and back to true. And only render if it's true.... so it would destroy and build again. Now, please understand we are talking about a hack from the very beginning. The best approach to me would be making a reset function to just clear the mess instead of trying to destroy/build the view. You could create an initialize method, call it on constructor and back again when you want to reset. – Bruno Reis May 30 '18 at 11:16
  • As I understand, view and state are two very separated concepts in React and it's important you understand that and make your best effort to do so, so that you can build better apps. – Bruno Reis May 30 '18 at 11:19
0

call this.componentWillMount()

Yash Ojha
  • 792
  • 9
  • 17
  • Please add more detail to your answer. Why does this work? What was the issue that you resolved? That makes it easier for OP and everyone in the future to understand their problem. – builder-7000 May 28 '18 at 22:18
  • this doesn't help it wouldn't restart the scene just go into the componentwill mount again.. all memory functions and veriables will stay the same as if the screen is already there. and not as if it starts it for the first time – Chief Madog May 29 '18 at 09:54