import React, { useState, useEffect, useContext, useRef } from 'react';
import Select from 'react-dropdown-select';
import { TokenContext } from '../../utilities/token-provider';
const NewsEditor = props => {
//context
const authTokens = useContext(TokenContext);
//refs
const titleRef = useRef();
const authorRef = useRef();
const bodyRef = useRef();
//state
const [articles, setArticles] = useState([]);
const [index, setIndex] = useState(null);
//run once
useEffect(async () => {
const result = await fetch(`${process.env.NEWS_URI}/news/metadata?limit=999`, {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
});
if (!result.ok) {
const err = `${result.status}: ${await result.text()}`;
console.log(err);
alert(err);
} else {
setArticles(await result.json());
}
}, []);
return (
News Editor
);
};
const handleSubmit = async (title, author, body, index, tokenFetch) => {
title = title.trim();
author = author.trim();
body = body.trim();
//fetch POST json data
const result = await tokenFetch(`${process.env.NEWS_URI}/news/${index}`, {
method: 'PATCH',
headers: {
'Content-Type': 'application/json',
'Access-Control-Allow-Origin': '*'
},
body: JSON.stringify({
title,
author,
body
})
});
if (!result.ok) {
return [`${result.status}: ${await result.text()}`];
}
return [null];
};
const handleDelete = async (index, tokenFetch) => {
const conf = confirm('Are you sure you want to delete this article?');
if (conf) {
const result = await tokenFetch(`${process.env.NEWS_URI}/news/${index}`, {
method: 'DELETE'
});
if (!result.ok) {
const err = `${result.status}: ${await result.text()}`;
return [err, false];
}
}
return [null, conf];
};
export default NewsEditor;