import React, { useState, useEffect } from 'react' import fetch from 'unfetch' import SubjectView from '../components/subjectView' import QuestionView from '../components/questionView' import LoadingIndicator from '../components/LoadingIndicator' import styles from './index.module.css' import constants from '../constants.json' const views = { subject: 'SUBJECT', question: 'QUESTION' } // TODO: // Add question on subjects view // question.data editor // save data to server / load it from there // save: save question count and subj count // save deleted/removed questions ? // edit \n-s in questions / answers // Load data: generate key / save keys as cookie and list? // Upload data: save to new / save to same as loaded export default function Index (props) { const [data, setData] = useState(null) const [view, setView] = useState(views.subject) const [error, setError] = useState(null) const setIndexes = (d) => { d.Subjects.forEach((subj, i) => { subj.ind = i subj.Questions.forEach((question, j) => { question.ind = j }) }) return d } useEffect(() => { console.info('Fetching data') fetch(`${constants.apiUrl}data.json`) .then((resp) => { if (resp && resp.ok) { return resp.json() } else { console.error('Error while fetching data') setError('Error while fetching data') } }) .then((resp) => { if (data) { console.warn('Tried to refetch data when it was still set!') } else { setData(setIndexes(resp)) } }) .catch((e) => { console.log(e) console.error('Error while fetching data') setError('Error while fetching data') }) }, []) if (error) { return (
{error}
) } const deleteQuestion = (subjInd, questionInd) => { data.Subjects[subjInd].Questions.splice(questionInd, 1) setData({ ...setIndexes(data) }) } const onChange = (subjInd, questionInd, newVal) => { data.Subjects[subjInd].Questions[questionInd] = newVal setData({ ...data }) } const renderView = () => { if (view === views.subject) { return ( ) } else if (view === views.question) { return ( ) } else { return (
No view!
) } } const downloadFile = async (data) => { const json = JSON.stringify(data) const blob = new Blob([json], { type: 'application/json' }) // eslint-disable-line const href = await URL.createObjectURL(blob) const link = document.createElement('a') link.href = href link.download = 'data.json' document.body.appendChild(link) link.click() document.body.removeChild(link) } if (!data) { return ( ) } return (
{ }} > Load data { }} > Upload data { downloadFile(data) }} > Download data
{ setView(views.subject) }}> Subject view { setView(views.question) }}> Question view
{renderView()}
) }