My function, getactivity(), pulls and sorts data from an API and returns the sorted data in answer1 format. However, I am facing a problem where whenever I run the function to retrieve the data, it keeps returning nothing.
Here is the full code:
import React, { Component, Fragment } from 'react';
import axios from 'axios';
import Pusher from 'pusher-js';
import Stats from '../../components/Stats';
import Layout from '../../components/Layout';
const choices = ['Monday', 'Tuesday', 'Wednesday', 'Thursday', 'Friday'];
let curr = new Date
let week = []
for (let i = 1; i <= 7; i++) {
let first = curr.getDate() - curr.getDay() + i
let day = new Date(curr.setDate(first)).toISOString().slice(0, 10)
week.push(day)
}
// console.log(week)
function getactivity() {
axios.get('/api/profiles/stats')
.then(response => {
const activity = response.data["Drinks"]
var o = {};
activity.forEach((i) => {
var Date = i.Date;
i.count = parseInt(i.count)
if (!o[Date]) {
return o[Date] = i
}
return o[Date].count = o[Date].count + i.count
})
var res = []
Object.keys(o).forEach((key) => {
res.push(o[key])
})
var answer1 = ""
for (const x of res) {
if(week.includes(x.Date)) {
answer1 = answer1 + "[" + x.Date + "]" + ": " + x.count + ", "
}
}
console.log("return: " + answer1)
return answer1
}, error => {
console.log(error);
});
}
console.log("act: " + getactivity())
class IndexPage extends Component {
state = { answers: getactivity() }
render() {
return (
<Layout pageTitle="AA Drinking activity">
<main className="container-fluid position-absolute h-100 bg-light">
<div className="row position-absolute w-100 h-100">
<section className="col-md-5 position-relative d-flex flex-wrap h-100 align-items-start align-content-between bg-white px-0">
<Stats choices={choices} stats={this.state.answers} />
</section>
</div>
</main>
</Layout>
);
}
};
export default () => (
<Fragment>
<IndexPage />
<style global jsx>{`
.custom-control-label {
background: transparent;
color: #999;
font-size: 2rem;
font-weight: 500;
cursor: pointer;
line-height: 2.25rem;
}
.custom-control-label:before, .custom-control-label:after {
top: 0;
left: -10px;
height: 2.25rem;
width: 2.25rem;
cursor: pointer;
box-shadow: none !important;
}
.custom-control-label.checked {
color: #007bff !important;
}
button.btn {
letter-spacing: 1px;
font-size: 1rem;
font-weight: 600;
}
`}</style>
</Fragment>
);
The order of the console.log() does not appear as expected. It prints in this order:
act: undefined
return: [2020-12-08]: 10, [2020-12-09]: 7, [2020-12-10]: 4, [2020-12-11]: 3,
I assumed that the return should be printed first.