javascriptreactjsreact-nativereact-native-chart-kit

Refresh Graph on button click


I am trying to create a button in my app which will refresh random data in a graph (made using react-native-chart-kit) using a React Native Button Component. My Code is below:

import * as React from 'react';
import {useState} from 'react';
import { StyleSheet, Text, View, Switch, Dimensions, Button, Alert } from 'react-native';
import { LineChart } from "react-native-chart-kit";
import Header from "./components/Header";
import Colors from "./constants/colors";


export default function App() {
  const [isEnabled, setIsEnabled] = useState(false);
  const toggleSwitch = () => setIsEnabled(previousState => !previousState);

  function refresh_data(){
    ...
    //Code here?
    ...
  }

  return (
    <View style = {styles.screen}>
      <View style = {styles.button}>
        <Button
          title="Refresh"
          color={Colors.primary}
          onPress={() => refresh_data}
        />
      </View>

      <View style = {styles.graph}>
        <View style = {{flex: 1}}>
          <Text style = {styles.text}>Bezier Line Chart</Text>
        </View>

        <View style={{flex: 2}}>
        <LineChart
          data={{
            labels: ["January", "February", "March", "April", "May", "June"],
            datasets: [{
              data: [
                Math.random() * 100,
                Math.random() * 100,
                Math.random() * 100,
                Math.random() * 100,
                Math.random() * 100,
                Math.random() * 100,
                Math.random() * 100,
                Math.random() * 100,
                Math.random() * 100,
                Math.random() * 100,
                Math.random() * 100,
                Math.random() * 100                
              ]
              }]
          }}
          width={Math.floor(Dimensions.get("window").width * 0.6)} // from react-native
          height={220}
          yAxisLabel="$"
          yAxisSuffix="k"
          yAxisInterval={1} // optional, defaults to 1
          chartConfig={{
            backgroundColor: "#e26a00",
            backgroundGradientFrom: "#fb8c00",
            backgroundGradientTo: "#ffa726",
            decimalPlaces: 2, // optional, defaults to 2dp
            color: (opacity = 1) => `rgba(255, 255, 255, ${opacity})`,
            labelColor: (opacity = 1) => `rgba(255, 255, 255, ${opacity})`,
            style: {
              borderRadius: 16
            },
            propsForDots: {
              r: "6",
              strokeWidth: "2",
              stroke: "#ffa726"
            }
          }}
          bezier
          style={{
            marginVertical: 8,
            borderRadius: 16
          }}
        />
      </View>

    </View>

  </View>
  );
}

const styles = StyleSheet.create({
  screen: {
  flex: 1,
  alignItems: 'stretch',
  justifyContent: 'center'
  },
  button: {
  alignSelf: 'center',
  justifyContent: 'center',
  flex: 1
  },
  graph: {
  flex: 3,
  alignItems: 'center',
  justifyContent: 'center'
  }
});

I'm pretty new to Javascript and React so this is likely a pretty basic question and I'd like to learn more than anything. One think I tried was having the entire page reload using location.reload() but that isn't what I am looking for (i know because it have a switch in another part of the app which refreshes the data whenever it is clicked, I just can't figure out how). Thanks in advance for any help!


Solution

  • Add some initial "random" data to component state, and in the refresh_data click handler set state with new "random" data.

    Also, the correct syntax for setting onClick callback is onClick={refresh_data} or onClick={() => refresh_data()}.

    export default function App() {
      const [randomData, setRandomData] = useState([
        Math.random() * 100,
        Math.random() * 100,
        Math.random() * 100,
        Math.random() * 100,
        Math.random() * 100,
        Math.random() * 100,
        Math.random() * 100,
        Math.random() * 100,
        Math.random() * 100,
        Math.random() * 100,
        Math.random() * 100,
        Math.random() * 100                
      ]);
    
      const [isEnabled, setIsEnabled] = useState(false);
      const toggleSwitch = () => setIsEnabled(previousState => !previousState);
    
      function refresh_data(){
        setRandomData([
          Math.random() * 100,
          Math.random() * 100,
          Math.random() * 100,
          Math.random() * 100,
          Math.random() * 100,
          Math.random() * 100,
          Math.random() * 100,
          Math.random() * 100,
          Math.random() * 100,
          Math.random() * 100,
          Math.random() * 100,
          Math.random() * 100                
        ])
      }
    
      return (
        <View style = {styles.screen}>
          <View style = {styles.button}>
            <Button
              title="Refresh"
              color={Colors.primary}
              onPress={refresh_data}
            />
          </View>
    
          <View style = {styles.graph}>
            <View style = {{flex: 1}}>
              <Text style = {styles.text}>Bezier Line Chart</Text>
            </View>
    
            <View style={{flex: 2}}>
            <LineChart
              data={{
                labels: ["January", "February", "March", "April", "May", "June"],
                datasets: [{ data: randomData }]
              }}
              width={Math.floor(Dimensions.get("window").width * 0.6)} // from react-native
              height={220}
              yAxisLabel="$"
              yAxisSuffix="k"
              yAxisInterval={1} // optional, defaults to 1
              chartConfig={{
                backgroundColor: "#e26a00",
                backgroundGradientFrom: "#fb8c00",
                backgroundGradientTo: "#ffa726",
                decimalPlaces: 2, // optional, defaults to 2dp
                color: (opacity = 1) => `rgba(255, 255, 255, ${opacity})`,
                labelColor: (opacity = 1) => `rgba(255, 255, 255, ${opacity})`,
                style: {
                  borderRadius: 16
                },
                propsForDots: {
                  r: "6",
                  strokeWidth: "2",
                  stroke: "#ffa726"
                }
              }}
              bezier
              style={{
                marginVertical: 8,
                borderRadius: 16
              }}
            />
          </View>
    
        </View>
    
      </View>
      );
    }
    

    There's a lot of repetition though, so I'd also create a random data utility:

    const createRandomData = (length = 10) => Array(length)
      .fill()
      .map(() => Math.random() * 100);
    

    const createRandomData = (length = 10) => Array(length).fill().map(() => Math.random() * 100);
    
    console.log(createRandomData(3));
    console.log(createRandomData(6));
    console.log(createRandomData(12));

    New usage:

    const [randomData, setRandomData] = useState(createRandomData(12));
    ...
    setRandomData(createRandomData(12));