I'm currently trying to render state
I see a few errors with declaring variables within the map loop.
Here is my attempt so far, Any help is welcomed
import React from "react";
import axios from "axios";
const transformHumanReadableDateToMessages = date => {
let d = new Date(date);
const days = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
];
return {
DayOfTheWeek: d.getDate(),
Month: d.getMonth(),
Day: days[d.getDay()],
YearAtTime: d.getFullYear()
};
};
export default class App extends React.Component {
state = {
messages: []
};
componentDidMount() {
axios.get(`https://api.myjson.com/bins/10xva4`).then(res => {
let result = res.data["messages"];
result = Array.from(new Set(result.map(e => JSON.stringify(e))));
result.reduce((accu, curr) => {
curr.date = transformHumanReadableDateToMessages(curr["sentAt"]);
accu.push(curr)
return accu;
}, []);
this.setState({
messages: result
});
});
}
render() {
return (
<>
{ this.state.messages.map(message =>
let d = new Date(date);
const days = [
"Sunday",
"Monday",
"Tuesday",
"Wednesday",
"Thursday",
"Friday",
"Saturday"
];
<div className="container">
<p>{message.content}<p/>
<p>{message.senderUuid}</p>
<p>DayOfTheWeek: {d.getDate()}
<p>Month: {d.getMonth()}</p>
<p>Day: {days[d.getDay()]}</p>
<p>Year: {d.getFullYear()} </p>
</div>
)}
</>
);
} }
For example each element in the JSON that is returned looks like this:
{
"sentAt":"2012-11-13T17:29:37.003Z",
"uuid": "435453",
"content": "1",
"senderUuid": "2"
}
I want to make the date more readable then add it to the element for a output like this:
{
"sentAt":"2012-11-13T17:29:37.003Z",
"uuid": "435453",
"content": "1",
"senderUuid": "2",
"DayOfTheWeek": 22,
"Month": 4,
"Day": 'Friday',
"YearAtTime": 2015
}
sentAtand/or current date property, why not only generate the values you need for display purposes duringrender(), which is the function that creates the actual bits users see? E.g.sentAtvalue, instead of trying to rely on another function or handler when I render the sate @Mike'Pomax'Kamermansrender()will still yield the same derived values. Your sorting reorders themessagesarray (not inrender(), in your handler for toggling sorting, usingsetState), and render then blindly regenerates the UI based on the updatedthis.state.messagesarray. That's how React works: you update the state in response to user actions, andrender()renders your UI based on the updated state.