I want to calculate the total of "No of vacancy column" values, so how to write a function or logic to calculate it?
const [vacancy, setVacancy] = useState([]);
console.log(vacancy[0].noOfVacancy) gives the first index output,but I put the for loop and try to get all the values, but its gives an error.
Finally, I want to get the sum/total of "No of vacancy column values"
The image is attached below
import React, { useEffect, useState, useRef } from "react";
import axios from "axios";
import jwt_decode from "jwt-decode";
import { useReactToPrint } from "react-to-print";
import image from "../../../images/back1.jpg";
export default function GenarateVacancyReport() {
const componentRef = useRef();
const handlePrint = useReactToPrint({
content: () => componentRef.current,
});
const [vacancy, setVacancy] = useState([]);
const [filteredResults, setFilteredResults] = useState([]);
const [searchInput, setSearchInput] = useState("");
const [companyName, setCompanyName] = useState("");
useEffect(() => {
const userToken = localStorage.userToken;
const decoded = jwt_decode(userToken);
setCompanyName(decoded.name);
let name = companyName;
console.log(name);
axios
.get(`http://localhost:5000/vacancy/get/name/${name}`)
.then((response) => {
setVacancy(response.data.exsitingVacancies);
});
}, [companyName]);
//search record
const searchItems = (searchValue) => {
setSearchInput(searchValue);
if (searchInput !== "") {
const filteredData = vacancy.filter((item) => {
return Object.values(item)
.join("")
.toLowerCase()
.includes(searchInput.toLowerCase());
});
setFilteredResults(filteredData);
} else {
setFilteredResults(vacancy);
}
};
CodePudding user response:
The code below should do the trick
useEffect(() => {
useEffect(() => {
let sumVacancies = 0;
for(let i = 0; i < vacancy.length; i ){
sumVacancies = vacancy[i].noOfVacancy;
let sum = vacancy.reduce((prev,curr) => prev.noOfVacancy
curr.noOfVacancy)
setTotal(sumVacancies);
}
setTotal(sum);
}, [vacancy])
or use reduce function
const [total, setTotal] = useState(0);
useEffect(() => {
let sum = vacancy.reduce((prev,curr) => prev.noOfVacancy
curr.noOfVacancy)
setTotal(sum);
}, [vacancy])
You can access the sum value from total