Home > Blockchain >  Multiplying an array in an API
Multiplying an array in an API

Time:05-30

I made an API call and had things working except I don't know exactly how to multiply this array of grades and render data onto the page and get an average percentage. Help me out?

import React, { useState, useEffect } from "react"; 
import axios from 'axios';


function Home() {
  const url = `https://api.hatchways.io/assessment/students`;
  const [students, setStudents] = useState(null);

  useEffect(() => {
    axios.get(url)
      .then(response => {
        setStudents(response.data)
      })
  }, [url])

  let content = null;

  if (students) {
    content =
    <div>
      <img 
        src={students.students[0].pic} 
        alt="robot" />
      <h1 className="h1">{students.students[0].firstName} 
    {students.students[0].lastName}</h1>
      <p>Email: {students.students[0].email}</p>
      <p>Company: {students.students[0].company}</p>
      <p>Skill: {students.students[0].skill}</p>
      <p>Average: {students.students[0].grades}</p>
      <p>Skill: {students.students[0].skill}</p>
    </div>
   }

  return (
    <div>
      {content}
    </div>
  )
}

export default Home;

Website

API Pulled from

CodePudding user response:

You want to loop over the students array.

Instead of:

<div>
<img 
  src={students.students[0].pic} 
  alt="robot" 
/>
<h1 className="h1">{students.students[0].firstName} 
  {students.students[0].lastName}</h1>
    <p>Email: {students.students[0].email}</p>
    <p>Company: {students.students[0].company}</p>
    <p>Skill: {students.students[0].skill}</p>
    <p>Average: {students.students[0].grades}</p>
    <p>Skill: {students.students[0].skill}</p>
</div>

You probably want something like:

(students.students.map((student) => <div>
<img 
  src={student.pic} 
  alt="robot" 
/>
<h1 className="h1">{student.firstName} 
  {student.lastName}</h1>
    <p>Email: {student.email}</p>
    <p>Company: {student.company}</p>
    <p>Skill: {student.skill}</p>
    <p>Average: {student.grades}</p>
    <p>Skill: {student.skill}</p>
</div>
)

CodePudding user response:

Make a function that calculate the avarage:

const getPercentage = (grades) => {
   const newGradeArrayWithInt = [];
   const gradeTotal = 0;
   grades.forEach(g => newGradeArrayWithInt.push(parseInt(g, 10)));
   newGradeArrayWithInt.forEach(ng => gradeTotal  = ng);
   return gradeTotal/2;   // This will get avarage percentage.
}

Use this function over here:

<p>Average: {getPercentage(students.students[0].grades)}</p>

  • Related