React Native - how to update FlatList of posts (new likes, ...)

Introduction

I am developing a list of posts, which is nested in a flatlist that has a pull to refresh implemented, and each post (rendered in a Card) has the avatar of the user who uploaded it. Also, it is possible for a user to change its avatar, so I need to update the posts FlatList with the new user avatar.

I have read something about the ExtraData prop but doesn't work in my case.

Code

// Posts Screen
export default function Posts(props) {
   const {
      userData: {
         username,
         avatar
      }
   } = props;

   const [data, setData] = useState([]); // [{ avatar, username, photoUri, likes }, ...]

   let previousAvatar = useRef(avatar).current;

   // ... Fetch the data
 
   // This is the wrong(?) stuff I am doing to update the FlatList
    useEffect(() => {
     if (previousAvatar !== avatar) {
       // For each post, change the avatar
       setPosts(
         posts.map((post) => ({
           ...post,
           avatar: avatar,
         }))
       );

       // Save the new avatar
       previousAvatar = avatar;
     }
   }, [ownerData]);


   return (<FlatList data={data} renderIt... />)
   
}

What I am doing

When I detect that the user has change its avatar, I modify the data which is passed to the FlatList, changing the avatar uri. I think this is bad, as there can be 100K posts in the list...

Also, I need to update the flatlist when new likes, new username, ... So I think this is not viable

What I have tried

// Posts Screen
export default function Posts(props) {
   const {
      userData
   } = props;

   ...
    
   return <FlatList data={data} extraData={userData} ... />

}

In the documentation says "By passing extraData to FlatList we make sure FlatList itself will re-render when the state changes.", but for me, this doesn't work, as userData is received via props.

Any ideas? Thank you.

1 answer

  • answered 2020-09-28 10:29 Mohammad K.

    flatList will render the data and not the extraData. try setting the extraData to a boolean and reverse the boolean value everytime you need to update the list.