// src/components/UploadPhoto.js
import React, { Component } from 'react'
import { connect } from 'react-redux'
import imageCompression from 'utils/imageCompression';
import ui from 'utils/ui'
import Input from 'components/Input'
import InputFile from 'components/InputFile'
import Textarea from 'components/Textarea'
import Button from 'components/Button'
import * as photoActions from 'redux/actions/photos'
import './UploadPhoto.scss'
// Set a limit of contents
const MAX_IMAGE_SIZE = 28000 // 28KB
const MAX_STRING_SIZE = 2000 // 2KB
class UploadPhoto extends Component {
handleInputChange = (e) => {
[e.target.name]: e.target.value,
handleFileChange = (e) => {
const file = e.target.files[0]
// If image size is bigger than MAX_IMAGE_SIZE(28KB),
// Compress the image to load it on transaction
if (file.size > MAX_IMAGE_SIZE) {
return this.compressImage(file)
const { file, fileName, location, caption } = this.state
this.props.uploadPhoto(file, fileName, location, caption)
compressImage = async (imageFile) => {
const MAX_IMAGE_SIZE_MB = MAX_IMAGE_SIZE / 100000 // 28KB
const compressedFile = await imageCompression(imageFile, MAX_IMAGE_SIZE_MB)
fileName: compressedFile.name,
warningMessage: '* Fail to compress image'
const { fileName, location, caption, isCompressing, warningMessage } = this.state
<form className="UploadPhoto" onSubmit={this.handleSubmit}>
className="UploadPhoto__file"
fileName={isCompressing ? 'Compressing image...' : fileName}
onChange={this.handleFileChange}
accept=".png, .jpg, .jpeg"
className="UploadPhoto__location"
onChange={this.handleInputChange}
placeholder="Where did you take this photo?"
className="UploadPhoto__caption"
onChange={this.handleInputChange}
placeholder="Upload your memories"
className="UploadPhoto__upload"
const mapDispatchToProps = (dispatch) => ({
uploadPhoto: (file, fileName, location, caption) =>
dispatch(photoActions.uploadPhoto(file, fileName, location, caption)),
export default connect(null, mapDispatchToProps)(UploadPhoto)