Home > Enterprise >  How to use extraData in a flatlist in react-Native
How to use extraData in a flatlist in react-Native

Time:01-05

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.

I found out I can solve this by using extraData={Reviews} in my flatlist. But this still does not work, what am I doing wrong?

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}
          extraData={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>
          )}
        />

CodePudding user response:

Use state when you need a change in data to cause a re-render in a component. Instead of

  let Reviews = [
    ...
  ]
  ...
  Reviews = // etc

Define and set your state with the useState hook.

  const existingReviews = [
    // your existing reviews
  ]; 
  const [reviews, setReviews] = useState(existingReviews);

  // to set
  setReviews(modifiedObj);

See more about state in the docs.

  • Related