Skip to content

Instantly share code, notes, and snippets.

@zackshapiro
Created June 14, 2019 23:15
Show Gist options
  • Save zackshapiro/4f394e5273a3296641ed25f0bf3e44a8 to your computer and use it in GitHub Desktop.
Save zackshapiro/4f394e5273a3296641ed25f0bf3e44a8 to your computer and use it in GitHub Desktop.
import { useReducer } from 'react'
// Constants
const LOADED = 'LOADED'
const INIT = 'INIT'
const PENDING = 'PENDING'
const FILES_UPLOADED = 'FILES_UPLOADED'
const UPLOAD_ERROR = 'UPLOAD_ERROR'
const initialState = {
files: [],
pending: [],
next: null,
uploading: false,
uploaded: {},
status: 'idle',
}
const reducer = (state, action) => {
switch (action.type) {
case 'load':
return { ...state, files: action.files, status: LOADED }
default:
return state
}
}
const useFileHandlers = () => {
const [state, dispatch] = useReducer(reducer, initialState)
const onChange = (e) => {
if (e.target.files.length) {
const arrFiles = Array.from(e.target.files)
const files = arrFiles.map((file, index) => {
const src = window.URL.createObjectURL(file)
return { file, id: index, src }
})
dispatch({ type: 'load', files })
}
}
return {}
}
export default useFileHandlers
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment