import React, { useState, useEffect } from 'react' import Head from 'next/head' import LoadingIndicator from '../components/LoadingIndicator.js' import QuestionSearchResult from '../components/QuestionSearchResult.js' import Subject from '../components/Subject.js' import SubjectSelector from '../components/SubjectSelector.js' import Sleep from '../components/sleep' import styles from './allQuestions.module.css' import constants from '../constants.json' const countReducer = (acc, subj) => { return acc + subj.Questions.length } function mergeData(data) { return data.reduce((acc, db) => { return [ ...acc, ...db.data.map((subj) => { return { ...subj, Name: `${subj.Name} [ DB: ${db.dbName} ]`, } }), ] }, []) } function fetchData(db) { return new Promise((resolve) => { fetch(`${constants.apiUrl}${db.path}`, { credentials: 'include', }) .then((resp) => { return resp.json() }) .then((resp) => { resolve({ dbName: db.name, data: resp, }) }) }) } function fetchAllData(dbs) { const promises = dbs.map((db) => { return fetchData(db) }) return Promise.all(promises) } function fetchDbs() { return new Promise((resolve) => { console.info('Fetching data') fetch(`${constants.apiUrl}getDbs`, { credentials: 'include', }) .then((resp) => { return resp.json() }) .then((data) => { resolve(data) }) }) } export default function AllQuestions({ router }) { const [subjectsShowing, setSubjectsShowing] = useState(false) const [searchTerm, setSearchTerm] = useState('') const [activeSubjName, setActiveSubjName] = useState('') const [dbs, setDbs] = useState(null) const [data, setData] = useState(null) const [fetchingData, setFetchingData] = useState(false) const subjectCount = data ? data.length : 0 const questionCount = data ? data.reduce(countReducer, 0) : 0 useEffect(() => { router.replace(`${router.asPath.replace('.html', '')}`, undefined, { shallow: true, }) // TODO: fix dis const querySearch = router.query.question ? decodeURIComponent(router.query.question) : '' console.log(querySearch) fetchDbs().then((res) => { setDbs(res) }) }, []) const renderDbSelector = () => { if (dbs) { return ( <> > ) } else { return null } } const renderSubjectBrowser = () => { let currSubj = data ? data.find((subj) => { return subj.Name === activeSubjName }) : {} return (