Hi,
I am doing a react chat app and I am trying to only display the last letโs say 3 chat messages. The code looks like this:
> import React, {useEffect, useReducer, useState} from "react";
> import {Box, Divider, Flex, Heading, HStack, Stack, Text, Textarea, VStack} from "@chakra-ui/react";
> import {useMoralis, useMoralisSubscription, useMoralisQuery} from "react-moralis";
> import classes from "./ViewMessages.module.css"
>
> function ViewMessages({id}) {
>
> const {isAuthenticated, user, Moralis} = useMoralis();
> const Terminal = Moralis.Object.extend("Terminal");
> const [chatMessages, setChatMessages] = useState([]);
>
> // Note that there is a limit!
> const [limit, setLimit] = useState(3);
>
> const fromIdQuery = new Moralis.Query(Terminal);
> fromIdQuery
> .equalTo("fromId", "240")
> .equalTo("toId", id)
> .descending("updatedAt")
>
> const toIdQuery = new Moralis.Query(Terminal);
> toIdQuery
> .equalTo("fromId", id)
> .equalTo("toId", "240")
> .descending("updatedAt")
>
> const mainQuery = Moralis.Query.or(fromIdQuery, toIdQuery).descending("updatedAt")
>
> const { data, error, isLoading } = useMoralisQuery(Terminal, query =>
> mainQuery
> .limit(limit)
> , []);
>
> useEffect(() => {
> if(data) {
> let chatHistory = JSON.stringify(data, null, 2)
> chatHistory = JSON.parse(chatHistory);
> //console.log("chatHistory", chatHistory);
> setChatMessages(chatHistory);
> }
> }, [data]);
>
> useMoralisSubscription(Terminal, q =>
> mainQuery
> , [], {
> onCreate: data => {
> let newMessage = JSON.stringify(data, null, 2)
> newMessage = JSON.parse(newMessage);
> let temp = [
> ...chatMessages,
> newMessage
> ];
> setChatMessages(temp);
> },
> enabled: true,
> });
>
>
> return (
> <VStack w="402px" h={"470px"}>
>
> {isLoading &&
> <Heading>Loading Messages</Heading>
> }
>
> {chatMessages && chatMessages.length > 0 &&
> <Flex flexDir={"column"} w={"100%"} overflow={"scroll"}>
> {chatMessages.map((item, index) => (
> <Stack key={index} p={2} m={1} border="1px solid #FCE8A4">
> <Text fontSize={"xl"} color={item.fromId === id ? "#1AFF80" : "#FFFFFF" }>STASH #{item.fromId} -> STASH #{item.toId}</Text>
> <Text fontSize={"xl"}>{item.message}</Text>
> </Stack>
> ))}
> </Flex>
> }
> </VStack>
> )
> }
>
> export default ViewMessages;
The table looks like this:
The code I have will display:
I want it do display the reverse order so: 2, 3, 4
What am I doing wrong? Any Ideas