-
Notifications
You must be signed in to change notification settings - Fork 0
/
Articles.js
61 lines (55 loc) · 2.01 KB
/
Articles.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
import React, { useEffect } from 'react'
import { Navigate } from 'react-router-dom'
import PT from 'prop-types'
import { axiosWithAuth } from '../axios/'
export default function Articles(props) {
// ✨ where are my props? Destructure them here
const { articles, getArticles, deleteArticle, setCurrentArticleId, currentArticleId } = props
// ✨ implement conditional logic: if no token exists
// we should render a Navigate to login screen (React Router v.6)
const isToken = localStorage.getItem('token')
if(!isToken){return (<Navigate to='/' replace={true} />)}
useEffect(() => {
// ✨ grab the articles here, on first render only
getArticles()
},[])
return (
// ✨ fix the JSX: replace `Function.prototype` with actual functions
// and use the articles prop to generate articles
<div className="articles">
<h2>Articles</h2>
{
!articles.length
? 'No articles yet'
: articles.map(art => {
return (
<div className="article" key={art.article_id}>
<div>
<h3>{art.title}</h3>
<p>{art.text}</p>
<p>Topic: {art.topic}</p>
</div>
<div>
<button disabled={currentArticleId} onClick={()=> setCurrentArticleId(art.article_id)}>Edit</button>
<button disabled={currentArticleId} onClick={()=> deleteArticle(art.article_id)}>Delete</button>
</div>
</div>
)
})
}
</div>
)
}
// 🔥 No touchy: Articles expects the following props exactly:
Articles.propTypes = {
articles: PT.arrayOf(PT.shape({ // the array can be empty
article_id: PT.number.isRequired,
title: PT.string.isRequired,
text: PT.string.isRequired,
topic: PT.string.isRequired,
})).isRequired,
getArticles: PT.func.isRequired,
deleteArticle: PT.func.isRequired,
setCurrentArticleId: PT.func.isRequired,
currentArticleId: PT.number, // can be undefined or null
}