Загрузка данных


import axios from 'axios';
import dayjs from 'dayjs';
import { useEffect, useRef, useState } from 'react';

import { axiosInstanceFormalization } from '@api/axios';
import {
  getFileMessageAttachment,
  getImageMessageAttachment,
} from '@components/ChatComponent/components/MessageListNoTrade/utils';
import icons from '@components/Icons';
import { commonDateFormat } from '@configs/standartDateFormat';
import { useAppSelect } from '@hooks/useAppSelector';

import { Icon } from '@uikit/Icon';
import { getChatName } from '@utils/getChatName';
import { getTextFromProp } from '@utils/noTradeChatFormMessage';
import { getChatMember } from '@widgets/NoTradeChat/utils/getChatMember';
import { ChatType } from 'types/NoTradeChat';

import { ChatListItemProps } from '../types';

export const useChatList = (props: ChatListItemProps) => {
  const { item, lastMessage } = props;

  const [localurl, setLocalurl] = useState('');

  const { chatId } = item;
  const imageAttachment = useAppSelect((state) =>
    getImageMessageAttachment(chatId ? state.chatSlice.chatContextMessages[chatId]?.message : undefined),
  );

  const fileAttachment = useAppSelect((state) =>
    getFileMessageAttachment(chatId ? state.chatSlice.chatContextMessages[chatId]?.message : undefined),
  );

  const currentUser = useAppSelect((state) => state.userSlice.info);

  const member = getChatMember(item, currentUser);

  const isFirmNameCanBeShow = member?.firmFullName && item.type !== ChatType.Group;

  const chatName = getChatName(item, isFirmNameCanBeShow, member);

  const { ChatGroup } = icons;

  const PinIcon = <Icon variant="pin" />;

  const formatedDate = (date: string) => {
    if (date) {
      return dayjs(date).format(commonDateFormat.dateFormat) === dayjs().format(commonDateFormat.dateFormat)
        ? dayjs(date).locale('ru').format(commonDateFormat.timeFormat)
        : dayjs(date).format(commonDateFormat.dateFormat);
    }
    return '';
  };

  const chatRef = useRef<HTMLDivElement>(null);

  useEffect(() => {
    const uri = getTextFromProp(lastMessage?.attachments?.[0], 'uri');
    if (lastMessage?.attachments && uri) {
      const source = axios.CancelToken.source();

      axiosInstanceFormalization
        .get(uri, {
          responseType: 'blob',
          cancelToken: source.token,
        })
        .then((response) => {
          const newUrl = URL.createObjectURL(response.data);
          setLocalurl(newUrl);
        });
    }
  }, [lastMessage]);

  return {
    PinIcon,
    formatedDate,
    localurl,
    currentUser,
    fileAttachment,
    imageAttachment,
    chatName,
    ChatGroup,
    chatId,
    member,
    chatRef,
  };
};