浏览代码

Update edit/create post

LenDoc 2 年之前
父节点
当前提交
f3d7e6bb80
共有 3 个文件被更改,包括 118 次插入52 次删除
  1. 10 1
      src/actions/index.js
  2. 34 11
      src/components/DropZone.js
  3. 74 40
      src/components/NewPost.js

+ 10 - 1
src/actions/index.js

@@ -140,6 +140,14 @@ export const uploadFile = (file) => {
     body: myForm,
   }).then((result) => result.json())
 }
+
+export const uploadFileType = {
+    name: 'photo',
+    action: `/upload`,
+    headers: localStorage.authToken
+    ? { Authorization: 'Bearer ' + localStorage.authToken }
+    : {},
+}
 export const actionUploadFile = (file) =>
   actionPromise('uploadFile', uploadFile(file))
 
@@ -172,7 +180,7 @@ export const actionAvatar = (imageId, myId) =>
     ),
   )
 
-export const actionPostUpsert = (post) => async (dispatch) => {
+export const actionPostUpsert = (post, _id) => async (dispatch) => {
   await dispatch(
     actionPromise(
       'postUpsert',
@@ -186,6 +194,7 @@ mutation PostUpsert($post:PostInput){
         {
           post: {
             ...post,
+            _id:_id,
             images: post.images.map(({ _id }) => ({ _id })),
           },
         },

+ 34 - 11
src/components/DropZone.js

@@ -2,7 +2,11 @@ import { useDropzone } from 'react-dropzone'
 import React, { useEffect } from 'react'
 import { Button,Image } from 'antd'
 import { UploadOutlined } from '@ant-design/icons'
-import { sortableContainer, sortableElement } from 'react-sortable-hoc'
+import { sortableContainer, SortableElement, sortableElement, SortableHandle } from 'react-sortable-hoc'
+import "antd/dist/antd.css"; // or 'antd/dist/antd.less'
+import { Upload } from "antd";
+import { uploadFileType } from '../actions'
+import { Row, Col } from 'antd'
 
 export function Basic({ onLoad }) {
   const { acceptedFiles, getRootProps, getInputProps } = useDropzone()
@@ -11,6 +15,8 @@ export function Basic({ onLoad }) {
       {file.path} - {file.size} bytes
     </li>
   ))
+  console.log('acceptedFiles name', acceptedFiles[0]?.name)
+
   // console.log('acceptedFiles',acceptedFiles)
   useEffect(() => {
     if (acceptedFiles) onLoad(acceptedFiles)
@@ -26,30 +32,47 @@ export function Basic({ onLoad }) {
     </section>
   )
 }
-
-export function ImageDemo({ _id, index, url }) {
-  return <SortableItem url={url} key={`item-${_id}`} index={index} />
-}
-export const SortableItem = sortableElement(({ url }) => {
+const videoRegularExp = / *\.(mp4|mkv|wmv|m4v|mov|avi|flv|webm|flac|mka|m4a|aac|ogg)/
+export const SortableItem = SortableElement(({ url, onRemoveImage, _id}) => {
   return (
-    <Image
+    <>
+ 
+    <img
       style={{
         // margin: '20px',
         maxWidth: '300px',
-        minWidth: '100px',
-
+          minWidth: '100px',
+          objectFit: 'cover',
         boxShadow: '0 5px 10px rgba(0,0,0,0.25), 0 10px 10px rgba(0,0,0,0.22)',
         maxHeight: '300px',
         minHeight:'100px'
       }}
       src={'/' + url}
     />
+        <Button
+    type="primary"
+    danger
+    size="small"
+        style={{
+          float: 'right',
+        margin:'5px'
+        }}
+    onClick={() => onRemoveImage(_id)}
+  >
+    {' '}
+    x{' '}
+      </Button>
+    </>
   )
 })
-export const SortableContainer = sortableContainer(({ children }) => {
+export const SortableContainer = sortableContainer(({ children ,checkLength}) => {
+
   return (
     <>
-      <ul style={{display:'flex', flexDirection:'row', margin:'5px'}}>{children}</ul>
+   
+          <ul style={{ display: 'flex', flexDirection: 'row', margin: '5px' }}>{children}</ul>
+   
+     
     </>
   )
 })

+ 74 - 40
src/components/NewPost.js

@@ -1,17 +1,14 @@
 import React, { useState, useEffect } from 'react'
-import {Link} from 'react-router-dom'
+import { Link } from 'react-router-dom'
 import { connect } from 'react-redux'
 import {
   actionUploadFiles,
-  actionPostUpsert
+  actionPostUpsert,
+  actionClearPromise,
 } from '../actions'
 import { actionClearPostsOne } from '../redux/reducers/post/postReducer'
 import { Button, message } from 'antd'
-import {
-  Basic,
-  SortableContainer,
-  SortableItem,
-} from '../components/DropZone'
+import { Basic, SortableContainer, SortableItem } from '../components/DropZone'
 import { arrayMoveImmutable } from 'array-move'
 import { Row, Col } from 'antd'
 
@@ -53,39 +50,58 @@ const PostEditor = ({
     params: { _id },
   },
   myID,
-  post,
+  post = {},
   onSave,
   onFileDrop,
   fileStatus,
   clearPostOne,
+  clearPromise,
 }) => {
   post = {
+    _id: post?._id || '',
     title: post?.title || '',
     text: post?.text || '',
     images: post?.images || [],
   }
 
+  console.log('post ', post)
+  console.log('post _id', _id)
   const [state, setState] = useState(post)
-  console.log('state', state)
-  console.log("какое щас айди", _id)
- 
-  
   useEffect(() => {
     if (_id === 'new' && Object.keys(post)) {
-      console.log("какое щас айди",_id === 'new' && Object.keys(post))
+      console.log('in condition')
       clearPostOne()
-      setState(post)
+      clearPromise('onePost')
+      if (post?._id?.length < 8) {
+        console.log('post with _id < 8', post)
+        post = {
+          _id: post?._id || '',
+          title: post?.title || '',
+          text: post?.text || '',
+          images: post?.images || [],
+        }
+        console.log('after post ', post)
+        console.log('update state', state)
+        return () => setState(post)
+      }
+
+      //console.log('post after clear ', post)
     }
   }, [_id])
-  console.log("post", post)
+
+  console.log('state after change', state)
+  console.log('post', post)
   useEffect(() => {
-    fileStatus?.status == 'FULFILLED' &&
+    if (fileStatus?.status === 'FULFILLED' && fileStatus?.payload != [])
       setState({
         ...state,
         images: [...state?.images, ...fileStatus?.payload],
       })
+    else if (fileStatus?.status === 'REJECTED') message.error('Error')
   }, [fileStatus])
 
+  console.log('images ', state?.images)
+
   const onSortEnd = ({ oldIndex, newIndex }) => {
     setState({
       ...state,
@@ -108,49 +124,66 @@ const PostEditor = ({
       ...state,
       images: state.images.filter((item) => item._id !== _id),
     })
-  const disabledBtn = state?.images && state?.title && state?.text ? false : true
+  const disabledBtn =
+    state?.images && state?.title && state?.text ? false : true
 
   const savePost = () =>
-    onSave(state) &&
+    onSave(state, state?._id) &&
     message.success(`Post published success!`) &&
     history.push(`/profile/${myID}`)
+  useEffect(() => {
+    return () => {
+      clearPromise('uploadFiles')
+      clearPromise('postUpsert')
+      clearPromise('post')
+      clearPostOne()
+      clearPromise('onePost')
+    }
+  }, [])
+  const checkLength = () => {
+    if (state?.images?.length > 8) {
+      console.log('state?.images?.length',state?.images?.length)
+      message.error('Error, upload Max 8 elements')
+      state["images"]=[]
+        return false
+    }
+    else {
+      return  <h3> {state?.images.length}/ 8</h3>
+    }
+}
   return (
     <section className="Post">
-    
-      <Row> 
-        <Col span={12} offset={6}>
-           <Basic onLoad={onFileDrop} />
-          <SortableContainer onSortEnd={onSortEnd}>
-            {(state?.images || []).map(({ _id, url }, index) => (
-              <div>  
-                <Button
-                  type="primary"
-                  danger
-                  size="small"
-                  style={{float:'right'}}
-                  onClick={() => onRemoveImage(_id)}
-                >
-                  {' '}
-                  x{' '}
-                </Button>
-                <SortableItem key={`item-${_id}`} index={index} url={url} />
-              
-              </div>
+      <Row>
+        <Col span={12} offset={7}>
+          <Basic onLoad={onFileDrop} />
+          <Col offset={1}>
+          <SortableContainer onSortEnd={onSortEnd} style={{ with: '300px' }}>
+          
+            { state?.images?.length<8 && (state?.images || []).map(({ _id, url }, index) => (
+             <SortableItem
+                key={`item-${_id}`}
+                url={url}
+                index={index}
+                onRemoveImage={onRemoveImage}
+                _id={_id}
+              /> 
             ))}
           </SortableContainer>
+            {checkLength()}
+            </Col>
         </Col>
       </Row>
 
       <h1 className="Title"> Title </h1>
       <Input
-        state={state.title || ''}
+        state={state?.title || ''}
         className="Input"
         onChangeText={onChangeTitle}
       />
       <h1 className="Title"> Text </h1>
 
       <Input
-        state={state.text || ''}
+        state={state?.text || ''}
         className="Input"
         onChangeText={onChangeText}
       />
@@ -180,5 +213,6 @@ export const CPostEditor = connect(
     onSave: actionPostUpsert,
     onFileDrop: actionUploadFiles,
     clearPostOne: actionClearPostsOne,
+    clearPromise: actionClearPromise,
   },
 )(PostEditor)