A Small collection of javascript code snippets I find myself using frequently. These are mostly here as a reminder to myself, but feel free to use them if they are of any use to you.
Convert Unix Time to human readable date
Netlify Lambda POST boiler plate with error handler and data check
React Componenet Class with Redux Store and defualt Reducer
const dateConvert =(UNIX_timestamp) => {
let a = new Date(UNIX_timestamp * 1000);
let months = ['Jan','Feb','Mar','Apr','May','Jun','Jul','Aug','Sep','Oct','Nov','Dec'];
let year = a.getFullYear();
let month = months[a.getMonth()];
let date = a.getDate();
let hour = a.getHours();
let min = a.getMinutes();
let sec = a.getSeconds();
let time = date + ' ' + month + ' ' + year + ' ' + hour + ':' + min + ':' + sec ;
return time;
}
module.exports = {
dateConvert : dateConvert
}
import dotenv from 'dotenv'
dotenv.config()
const statusCode = 200
const headers = {
'Access-Control-Allow-Origin': '*',
'Access-Control-Allow-Headers': 'Content-Type',
}
exports.handler = function(event, context, callback) {
// basic error handler to respond back to request source if there's an issue
const handleError = (message) => {
callback(null, {
statusCode,
headers,
body: JSON.stringify({ type: message }),
})
}
// We only want to respond if this is a POST request.
if (event.httpMethod !== 'POST' || !event.body) {
handleError('Please use POST')
return
}
// Parse Post body back into JSON object
let data = JSON.parse(event.body)
// Verify expected data is present
if (
!data.id ||
!data.name
) {
handleError('missing data in request')
return
}
// echo request to verify everythign is set up, can be removed once logic is entered.
callback(null, {
statusCode,
headers,
body: event.body,
})
}
import React, { Component } from 'react'
import { connect } from 'react-redux'
class ClassName extends Component {
// this assumes a reducer with the UPDATE_STATE case.
updateState = (item, value) => {
this.props.dispatch({ type: 'UPDATE_STATE', item: item, value: value })
}
render() {
return (
<div>
{console.log(this.props.data)}
Hello World
</div>)
}
}
const mapStateToProps = state => {
return {
data: state.data,
}
}
export default connect(mapStateToProps)(ClassName)