import {useEffect, useRef, useState} from "react";
import store from "../reducers/reducers";
import {ConnectPostDraw} from "./PostsDraw";
import {connect} from "react-redux";
import {actionGetPosts} from "../action/action";

const Post = ({posts = [], getPosts}) => {

    useEffect(()=>{
        getPosts();
    }, [])

    useEffect(()=>{
        setNewPosts(newPosts.concat(posts))
    }, [posts])

    let ref = useRef(null)
    let [skip, setSkip] = useState(100)
    let [newPosts, setNewPosts] = useState([])

    let scrollHandler = () => {
        if (ref.current.scrollTop + ref.current.clientHeight === ref.current.scrollHeight) {
            getPosts(skip)
            setSkip(skip+100)
        }
    }
    useEffect(()=>{
        getPosts();
    }, [])

    useEffect(()=>{
        setNewPosts(newPosts.concat(posts))
    }, [posts])

    // console.log(store.getState())

    return (
        <main>
            <div className="wrapper" ref={ref} onScroll={()=>scrollHandler()}>
                {newPosts.map(post=><ConnectPostDraw post = {post}/>)}
            </div>
        </main>
    )
}
export const ConnectPosts = connect(state=>({posts: state?.promise?.allPosts?.payload?.data?.PostFind}), {getPosts: actionGetPosts})(Post)

