Search code examples
javascriptreactjsreact-nativearray-map

React Native never[] array map returns null How can I fix it?


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


Solution

  • Hao Wu's comment solved the problem:

    It didn't update because the reference of chats never changed. Pushing element into it won't trigger rerender, even with calling setChats(data) which ultimately is itself. A quick fix is to set it as a new reference when setting chats: setChats([ ...data ]);