import React, { FC, useEffect } from 'react'
import { useSelector, useDispatch } from 'react-redux'
import { useHistory } from 'react-router-dom'

import { handleApiError } from '../api/errors'
import { fetchTimeline } from '../actions/posts'
import { getTimeline } from '../selectors/posts'
import { getAuthenticated } from '../selectors/authentication'

import { AppThunkDispatch } from '../types'

import PostList from '../components/post-list'

const Timeline: FC = () => {
    const authenticated = useSelector(getAuthenticated)
    const posts = useSelector(getTimeline)
    const dispatch = useDispatch<AppThunkDispatch>()
    const history = useHistory()

    useEffect(() => {
        const init = async () => {
            try {
                await dispatch(fetchTimeline())
            } catch (err) {
                handleApiError(err, dispatch, history)
            }
        }

        if (authenticated) init()
    }, [authenticated])

    return <PostList posts={posts} />
}

export default Timeline
