import React, {useState} from 'react'; import {postJson} from '../api'; import {daysBefore, localToday} from '../dates'; import {errorMessages} from '../errors'; import Modal from './Modal'; import WhenPicker from './WhenPicker'; const WHEN_CHOICES = [['today', 'Today'], ['tomorrow', 'Tomorrow'], ['other', 'Another day']]; // Adding a job, as a dialog over the page: what needs doing, when, and a note // if they want one. Saves with POST /jobs.json and hands the job to onSaved. export default function AddJobModal({onClose, onSaved}) { const [name, setName] = useState(''); const [description, setDescription] = useState(''); const [noting, setNoting] = useState(false); // the notes box is open const [when, setWhen] = useState('today'); const [customDate, setCustomDate] = useState(''); const [saving, setSaving] = useState(false); const [errors, setErrors] = useState([]); const today = localToday(); const dueOn = {today, tomorrow: daysBefore(today, -1), other: customDate}[when]; function chooseWhen(choice) { setWhen(choice); if (choice === 'other' && !customDate) setCustomDate(today); } async function save(event) { event.preventDefault(); setSaving(true); setErrors([]); try { const {ok, status, data} = await postJson('/jobs.json', { job: {name, description, due_date: dueOn}, }); if (ok) { onSaved(data); return; } setErrors(errorMessages(status, data, {signedOut: 'Please sign in again to add this job.'})); } catch (error) { setErrors(['Couldn\'t reach the server. Please try again.']); } setSaving(false); } return (
{errors.length > 0 && (