Fix rendering of events in Availability & refactor

- Possible dates were not ordered by dates, which in turn crashed
the rendering of Availability component
- Token was not added to headers after login
- Refactor Schedule by removing useless UseEffect
- Simplify rendering of events in Selected Dates (for now)
This commit is contained in:
rui hildt 2020-09-02 23:08:41 +02:00
parent 8dbe2185de
commit 6cc19211c1
8 changed files with 35 additions and 46 deletions

View File

@ -30,7 +30,7 @@
}, },
"scripts": { "scripts": {
"start": "react-app-rewired start", "start": "react-app-rewired start",
"dev": "PORT=8000 BROWSER=firefox-developer-edition react-app-rewired start", "dev": "BROWSER=firefox-developer-edition react-app-rewired start",
"build": "react-app-rewired build", "build": "react-app-rewired build",
"test": "react-app-rewired test", "test": "react-app-rewired test",
"eject": "react-app-rewired eject" "eject": "react-app-rewired eject"

View File

@ -22,7 +22,7 @@ export default function App() {
const [isAuthenticated, setIsAuthenticated] = useState(!!existingToken); const [isAuthenticated, setIsAuthenticated] = useState(!!existingToken);
const [currentUser, setCurrentUser] = useState(existingUser || ''); const [currentUser, setCurrentUser] = useState(existingUser || '');
const [participant, setParticipant] = useState(); const [participant, setParticipant] = useState();
const [possibleDates, setPossibleDates] = useState(); const [possibleDates, setPossibleDates] = useState([]);
const [currentMeeting, setCurrentMeeting] = useState({ const [currentMeeting, setCurrentMeeting] = useState({
title: '', title: '',
description: '', // optional description: '', // optional

View File

@ -28,10 +28,7 @@ export default function IntervalSelector({
.toFormat('yyyy-MM-dd'); .toFormat('yyyy-MM-dd');
// Create an event dates list used to create the days columns // Create an event dates list used to create the days columns
const daysList = []; const daysList = selectedDates.map((event) => event.start);
selectedDates.forEach((event) => {
daysList.push(event.start);
});
const handleDayDidMount = (info) => { const handleDayDidMount = (info) => {
let currentDate = DateTime.fromJSDate(info.date).toFormat('yyyy-MM-dd'); let currentDate = DateTime.fromJSDate(info.date).toFormat('yyyy-MM-dd');

View File

@ -1,13 +1,12 @@
import React from 'react'; import React from 'react';
import { Divider, Icon, IconButton } from 'rsuite'; import { Divider, Icon, IconButton } from 'rsuite';
export default function SelectedDates({ datesList, handleDelete }) { export default function SelectedDates({ possibleDates, handleDelete }) {
return ( return (
<ul> <ul>
{datesList.map((date) => ( {possibleDates.map((date) => (
<li key={date}> <li key={date.start}>
{date.setLocale('en-gb').toLocaleString()} {date.start}
{` (${date.weekdayShort})`}
<Divider vertical /> <Divider vertical />
<IconButton <IconButton
icon={<Icon icon='close' />} icon={<Icon icon='close' />}

View File

@ -1 +1 @@
export const API_URL = 'http://localhost:3000/api'; export const API_URL = 'http://localhost:9000/api';

View File

@ -10,6 +10,7 @@ export const backend = axios.create({
}, },
}); });
// Add token if already in local storage
if (existingToken) { if (existingToken) {
backend.defaults.headers.common['Authorization'] = JSON.parse(existingToken); backend.defaults.headers.common['Authorization'] = JSON.parse(existingToken);
} }

View File

@ -129,7 +129,7 @@ export default function Availability({
}); });
}; };
if (!possibleDates) { if (possibleDates.length === 0) {
return <Redirect to='/dashboard' />; return <Redirect to='/dashboard' />;
} }

View File

@ -1,4 +1,6 @@
import React, { useState, useEffect } from 'react'; import React, { useState } from 'react';
import { DateTime } from 'luxon';
import { useHistory } from 'react-router-dom';
import { import {
Panel, Panel,
Form, Form,
@ -10,8 +12,6 @@ import {
Message, Message,
FormGroup, FormGroup,
} from 'rsuite'; } from 'rsuite';
import { DateTime } from 'luxon';
import { useHistory } from 'react-router-dom';
import { import {
NavBar, NavBar,
@ -20,6 +20,8 @@ import {
SelectedDates, SelectedDates,
} from '../components'; } from '../components';
import { backend } from '../helpers/http-common'; import { backend } from '../helpers/http-common';
import { useAuth } from '../helpers/authContext';
import { durations } from '../assets/data/durations'; import { durations } from '../assets/data/durations';
import './styles/Schedule.less'; import './styles/Schedule.less';
@ -32,22 +34,11 @@ export default function Schedule({
setParticipant, setParticipant,
}) { }) {
const [eventsList, setEventsList] = useState([]); const [eventsList, setEventsList] = useState([]);
const [datesList, setDatesList] = useState(eventsToDates(eventsList));
const [durationIdx, setDurationIdx] = useState(0); const [durationIdx, setDurationIdx] = useState(0);
const [error, setError] = useState(false); const [error, setError] = useState(false);
const history = useHistory(); const history = useHistory();
const { authToken } = useAuth();
useEffect(() => {
// Push the selected dates up the state tree
// but keep all related logic here
setPossibleDates(eventsList);
}, [eventsList, setPossibleDates]);
useEffect(() => {
let updatedDates = eventsToDates(eventsList).sort();
setDatesList(updatedDates);
}, [eventsList]);
// EVENTS & DATES // EVENTS & DATES
const handleSelectDates = (info) => { const handleSelectDates = (info) => {
@ -105,7 +96,14 @@ export default function Schedule({
updatedEvents.push({ start: date, display: 'background' }); updatedEvents.push({ start: date, display: 'background' });
}); });
} }
// Sort by date
updatedEvents.sort(
(date1, date2) => Date.parse(date1.start) - Date.parse(date2.start),
);
setEventsList(updatedEvents); setEventsList(updatedEvents);
setPossibleDates(updatedEvents);
}; };
const handleDelete = (date) => { const handleDelete = (date) => {
@ -137,6 +135,9 @@ export default function Schedule({
// MEETING // MEETING
const handleSchedule = () => { const handleSchedule = () => {
// Add token to the request
backend.defaults.headers.common['Authorization'] = authToken;
// ADD THE MEETING // ADD THE MEETING
backend backend
.post('/meetings', currentMeeting) .post('/meetings', currentMeeting)
@ -155,7 +156,6 @@ export default function Schedule({
host: 1, host: 1,
answered: 0, answered: 0,
}); });
history.push('/availability');
}) })
.catch((error) => { .catch((error) => {
setError('Failed to add new meeting.'); setError('Failed to add new meeting.');
@ -198,18 +198,19 @@ export default function Schedule({
.then(function (results) { .then(function (results) {
const addID = ({ data }) => { const addID = ({ data }) => {
let possibleDate = { let possibleDate = {
id: data.id,
start: data.possible_date.substring(0, 10), start: data.possible_date.substring(0, 10),
display: 'background', display: 'background',
id: data.id,
}; };
return possibleDate; return possibleDate;
}; };
const possibleDatesWithID = results.map((result) => const possibleDatesWithID = results
addID(result), // Add id
); .map((result) => addID(result));
setPossibleDates(possibleDatesWithID); setPossibleDates(possibleDatesWithID);
history.push('/availability');
}) })
.catch((error) => { .catch((error) => {
setError("Couldn't add possible dates to the meeting."); setError("Couldn't add possible dates to the meeting.");
@ -289,7 +290,7 @@ export default function Schedule({
appearance='ghost' appearance='ghost'
block block
size='lg' size='lg'
disabled={datesList.length === 0} disabled={possibleDates.length === 0}
onClick={() => handleClear()} onClick={() => handleClear()}
> >
Clear selection Clear selection
@ -298,7 +299,7 @@ export default function Schedule({
appearance='primary' appearance='primary'
size='lg' size='lg'
block block
disabled={datesList.length === 0} disabled={possibleDates.length === 0}
onClick={handleSchedule} onClick={handleSchedule}
> >
Confirm dates Confirm dates
@ -306,10 +307,10 @@ export default function Schedule({
</ButtonGroup> </ButtonGroup>
{error && <Message type='error' description={error} />} {error && <Message type='error' description={error} />}
<div className={'selected-dates'}></div> <div className={'selected-dates'}></div>
{datesList.length > 0 && ( {possibleDates.length > 0 && (
<> <>
<SelectedDates <SelectedDates
datesList={datesList} possibleDates={possibleDates}
handleDelete={handleDelete} handleDelete={handleDelete}
/> />
</> </>
@ -332,12 +333,3 @@ export default function Schedule({
</> </>
); );
} }
// Convert events to Luxon Datetime objects
const eventsToDates = (events) => {
let dates = [];
events.forEach((event) => {
dates.push(DateTime.fromFormat(event.start, 'yyyy-MM-dd'));
});
return dates;
};