import React, { useState, useEffect, useMemo } from 'react'; import { useParams } from 'react-router-dom'; import { Helmet } from 'react-helmet'; import localForage from 'localforage'; import { sourceLink, infoLine, ToggleDot } from './utils.js'; function Article({ cache }) { const { id } = useParams(); if (id in cache) console.log('cache hit'); const [story, setStory] = useState(cache[id] || false); const [error, setError] = useState(''); const [pConv, setPConv] = useState([]); useEffect(() => { localForage.getItem(id) .then( (value) => { if (value) { setStory(value); } } ); fetch('/api/' + id) .then(res => { if (!res.ok) { throw new Error(`Server responded with ${res.status} ${res.statusText}`); } return res.json(); }) .then( (result) => { setStory(result.story); localForage.setItem(id, result.story); }, (error) => { const errorMessage = `Failed to fetch new article content (ID: ${id}). Your connection may be down or the server might be experiencing issues. ${error.toString()}.`; setError(errorMessage); } ); }, [id]); const pConvert = (n) => { setPConv(prevPConv => [...prevPConv, n]); }; const nodes = useMemo(() => { if (story && story.text) { let div = document.createElement('div'); div.innerHTML = story.text; return div.childNodes; } return null; }, [story]); return (
{error &&
Connection error? Click to expand.

{error}

{story &&

Loaded article from cache.

}
} {story ?
{story.title} | QotNews

{story.title}

Source: {sourceLink(story)}
{infoLine(story)} {nodes ?
{Object.entries(nodes).map(([k, v]) => pConv.includes(k) ? {v.innerHTML.split('\n\n').map((x, i) =>

)} : (v.nodeName === '#text' ?

{v.data}

: {v.localName === 'pre' && } ) )}
:

Problem getting article :(

}
:

Loading...

}
); } export default Article;