import React, { useState, useRef } from 'react'; import { useHistory } from 'react-router-dom'; function Submit() { const [progress, setProgress] = useState(null); const inputRef = useRef(null); const history = useHistory(); const submitArticle = (event) => { event.preventDefault(); const url = event.target[0].value; inputRef.current.blur(); setProgress('Submitting...'); let data = new FormData(); data.append('url', url); fetch('/api/submit', { method: 'POST', body: data }) .then(res => { if (res.ok) { return res.json().then(data => ({ ok: true, data: data })); } // Handle error responses return res.json() .then(data => ({ ok: false, data: data })) // Our API's JSON error .catch(() => { // Not a JSON error from our API, so it's a server issue throw new Error(`Server responded with ${res.status} ${res.statusText}`); }); }) .then( ({ ok, data }) => { if (ok) { history.replace('/' + data.nid); } else { setProgress(data.error || 'An unknown error occurred.'); } }, (error) => { setProgress(`Error: ${error.toString()}`); } ); } return (
{progress ? progress : ''}
); } export default Submit;