Search code examples
javascriptreact-nativesvgvictory-charts

Fetch data to React Native Victory charts


I managed to create an object that holds both key(service name) and value(counter of each service) What i dont get is how i fetch the data properly to the graph, meaning that the X axis will hold the key(Service name) and Y axis will hold the value(counter)

Code of creating the object:

const servicesCounter = services.reduce((counterObj, service) => { //Reduce => reduce the array to a single value, then count it.
    if (counterObj.hasOwnProperty(service)) {
      counterObj[service] += 1;
      return counterObj;
    }
  
    return {
      ...counterObj,
      [service]: 1
    };
  }, {});

Console Log:

Service Counter =>  Object {
  "clean": 4,
  "haircut": 3,
  "wash": 1,
}

Victory Pie:

  data={[
    { x: "One" /*Here i need to present the key(service name) */ , y: 2 /*Here i need to present the value(counter)*/},
    { x: "Two", y: 4 },
    { x: "Three", y: 3 }
  ]}

Firestore query to get the service names:

  useEffect(() => { //Query to get the services from database and count them to later use.
    firebase
    .firestore()
    .collection("users")
    .doc(uid)
    .collection("confirmed-appointments").get().then((querySnapshot) => {
      let arrayofServices = [];
      querySnapshot.forEach((doc) => {
        arrayofServices.push(doc.data().serviceType)
      })
      //console.log("Array of services ", arrayofServices);
      setServices(arrayofServices);
    })
    
  }, [])

Any Suggestions that will make my life easier please??


Solution

  • You can use object.entries and iterate through the properties and create an array for the chart and use it in the chart. you can run the snippet below.

    const data = {
      "clean": 4,
      "haircut": 3,
      "wash": 1,
    };
    
    const arr = new Array();
    
    for (const [key, value] of Object.entries(data)) {
      arr.push({x:key,y:value});
    }
    
    console.log(arr)