Home > Enterprise >  How to re-render a flatList in react-native without using redux
How to re-render a flatList in react-native without using redux

Time:01-04

I'm making a reviewsection, I have an array with 2 existing reviews. When the user writes a review and pressed the post button the post gets added into the array using destructuring. This works when I do a console.log() of the array I see the new data being inserted but my flatList is not updated and still only shows my 2 previously existing reviews.

initial array:

let Reviews = [
    {
      title: "I love F1",
      name: "Tibo Mertens",
      review:
        "This car may have a legendary driver on their team, but unfortunately, their car doesn't live up to his skills",
    },
    {
      title: "F1 is awesome",
      name: "Quintt Adam",
      review:
        "This car is extremely middle of the pack when it comes to the best car on the grid of 2022",
    },
  ];

Destructuring function that gets called when the button is pressed:

const addReview = (title, name, review) => {
    const newReview = { title: title, name: name, review: review };

    const modifiedObj = {
      title: newReview.title,
      name: newReview.name,
      review: newReview.review,
    };

    Reviews = [modifiedObj, ...Reviews];

    console.log(Reviews);
  };

My flatList:

<FlatList
          data={Reviews}
          renderItem={({ item }) => (
            <View style={styles.listContainer}>
              <View style={styles.reviewContainer}>
                <Text style={styles.reviewTitle}>{item.title}</Text>
                <Text style={styles.review}>{item.review}</Text>
                <Text style={styles.reviewName}>- {item.name}</Text>
              </View>
            </View>
          )}
        />

I'm very new to React-native and do not know how to use redux like other solutions on stackoverflow said I could use, I want to do it without redux.

CodePudding user response:

The FlatList component is a PureComponent and will not re-render if the props don't show any changes.

The documentation suggests using the extraData prop on your FlatList component to re-render itself when the styles state changes.

CodePudding user response:

You can use local state with hooks (or class components):

Hooks example:

const [reviews, addReview] = useState(Reviews);

<button onClick={() => addReview([newReview, ...reviews])}>Add review</button>

When state updates it will trigger a re-render cause your new review to show on the screen.

  • Related