skip to Main Content

I created an empty state array than push data in it from firebase.

const [chats, setChats] = useState([]);

When I use console.log(chats) function, it returns me the array correctly

useEffect(() => {
    async function GetChats() {
      const data = chats;
      const querySnapshot = await getDocs(collection(db, "chat"));
      querySnapshot.forEach((doc) => {
        data.push({
          id: doc.id,
          data: doc.data(),
        });
        setChats(data);
      });
    }
    GetChats();
  }, []);
console.log(chats)

Console:

  1. [{…}]

    1. 0:

      1. data: {cinsiyet: 'erkek', memleket: 'rize', name: 'kutay akgün'}

      2. id: "Kutay"

      3. [[Prototype]]: Object

    2. 1:

      1. data: {memleket: 'Rize', name: 'Ali Aydın', cinsiyet: 'Erkek'}

      2. id: "Ali"

      3. [[Prototype]]: Object

    3. 2:

      1. data: {cinsiyet: 'Kadın', name: 'Fatma Aydın', memleket: 'Rize'}

      2. id: "Fatma"

      3. [[Prototype]]: Object

    4. 3:

      1. data: {cinsiyet: 'Erkek', memleket: 'Rize', name: 'Kutay Aydın'}

      2. id: "Kutay"

      3. [[Prototype]]: Object

    5. length: 4

    6. [[Prototype]]: Array(0)

NO PROBLEM UP TO THIS POINT

But than when I try to render array to a component with map function it returns noting. I use return too but it doesn’t work.

 return (
    
    <SafeAreaView>
      <ScrollView>
      {
          chats.map((chat) => {
            return (
            
              <Text key={chat.id}>{chat.data.name}</Text>
            );
          })
          
      
     }
      </ScrollView>
    </SafeAreaView>
  );

chats array type was never[]. To fix it I add one data manually to define type of the array

const [chats, setChats] = useState([{id: "Kutay",data:{cinsiyet: "erkek", memleket: "rize", name: "kutay akgün"}}]);

now this is how it is:

const chats: {
    id: string;
    data: {
        cinsiyet: string;
        memleket: string;
        name: string;
    };
}[]

which is true at all.

But now when I try to render array. It only renders the first element which I added manually.

How can I make possible to render other elements too.??

enter image description here

2

Answers


  1. Chosen as BEST ANSWER

    @Hao Wu's comment solved the problem.


  2. You shouldn’t be using async in useEffect, that’s why React "yells" at you when you try to do it.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search