Trung
Trung

Reputation: 31

How to re render FlatList React Native when working with redux

I am new to React Native, I'm having trouble with FlatList. I assign extraData to a redux value but it does not re-render the FlatList when redux update. I think I should assign it to a local state, but I got too many re render error. Many thanks to anyone who help me! Below is my code

function CartScreen() {
const cart = useSelector((state) => state.cartReducer);
console.log(cart);
const dispatch = useDispatch();

useEffect(() => {
    dispatch(cartActions.refreshCartAction(cart));
}, []);

const renderItem = ({ item }) => {
    return <CartItem book={item} />;
};

return (
    <View>
        <FlatList
            data={cart}
            renderItem={renderItem}
            keyExtractor={(item) => item._id.toString()}
            extraData={cart}
        />
    </View>
);
}

export default CartScreen;

Upvotes: 2

Views: 1294

Answers (2)

Trung
Trung

Reputation: 31

I found an error in my redux action that solve the problem. Thank everyone!!

Upvotes: 1

Yoel
Yoel

Reputation: 7985

If the data in the global state is asynchronous You'll have to do that

{cart  && <FlatList
          data={cart}
          renderItem={renderItem}
          keyExtractor={(item) => item._id.toString()}
          extraData={cart}
       />
}

Upvotes: 1

Related Questions