Created
June 14, 2019 23:15
-
-
Save zackshapiro/4f394e5273a3296641ed25f0bf3e44a8 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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