Скролит не туда, потому что, скорее всего, ты не реализовал getItemLayout.
Можешь перепроверить малой кровью - сделай ВСЕ сообщения одной высоты, и попробуй скроллить к элементу.
Вс1 равно не очень работает
Можете посмотреть хук?
Может приглянётся какая то проблема которую я не замечаю?
import { RefObject, useCallback, useLayoutEffect, useRef, useState } from "react";
import { FlatList, InteractionManager } from "react-native";
import { ApiResponseError } from "@/api/types";
import { Message } from "@/features/chat/entity";
type UseScrollToMessageProps = {
getMessages: (
messageId: string,
direction: { prev?: number; next?: number }
) => Promise<[ApiResponseError, null] | [null, Message[]]>;
updateConversation: React.Dispatch<React.SetStateAction<Message[]>>;
conversation: Message[];
fetchSize?: number;
scrollListRef?: RefObject<FlatList<Message>>;
};
const useScrollToMessage = ({
getMessages,
updateConversation,
conversation,
fetchSize = 15,
scrollListRef
}: UseScrollToMessageProps) => {
const [targetId, setTargetId] = useState<string | null>(null);
const fetchedMessages = useRef<Message[]>([]);
const conversationRef = useRef<Message[]>(conversation);
const scrollToMessage = useCallback(
async (messageId: string) => {
const existingIndex = conversation.findIndex(msg => msg.id === messageId);
// Check if the message is already fetched, then scroll to it
if (existingIndex !== -1) {
// Already exists, scroll directly
setTargetId(messageId);
InteractionManager.runAfterInteractions(() => {
scrollListRef?.current?.scrollToIndex({ index: existingIndex, animated: true, viewPosition: 0.5 });
});
return;
}
// Fetch around the target message
const [error, msgs] = await getMessages(messageId, {
prev: fetchSize,
next: fetchSize
});
if (error || !msgs) return;
fetchedMessages.current = msgs;
// Check if the fetched messages are already in the conversation
updateConversation(prev => {
const newMsgs = [...prev, ...fetchedMessages.current]
.filter(msg => !prev.some(existingMsg => existingMsg.id === msg.id))
.sort((a, b) => b.createdAt.getTime() - a.createdAt.getTime());
conversationRef.current = newMsgs;
return newMsgs;
});
setTargetId(messageId);
},
[conversation, fetchSize, getMessages, updateConversation, scrollListRef]
);
useLayoutEffect(() => {
if (!targetId) return;
const newIndex = conversationRef.current.findIndex(msg => msg.id === targetId);
if (newIndex === -1) return;
setTimeout(() => {
scrollListRef?.current?.scrollToIndex({
index: newIndex ?? 0,
animated: true,
viewPosition: 0.5,
viewOffset: 0
});
}, 500);
setTargetId(null);
}, [targetId, updateConversation, scrollListRef]);
return { scrollTargetId: targetId, scrollToMessage };
};
export default useScrollToMessage;