简体   繁体   中英

First click not rendering correct data [second click works]?

I have a menu here, made with a horizontal flatlist:

在此处输入图像描述

Code for menu:

<View style={{ position: 'absolute', left: 0, top: 0 }}>
    <FlatList
      horizontal
      data={categories}
      extraData={
      selectedCategory // for single item
    }
      style={styles.flatList}
      renderItem={({ item: rowData }) => (
        <TouchableOpacity
          onPress={() => recalculateCategory(rowData)} 
          style={rowData === selectedCategory ? styles.selected : styles.unselected}
        >
          <Text style={{ fontWeight: 'bold', color: '#FFFFFF', padding: 6 }}>
            { rowData }
          </Text>

        </TouchableOpacity>
      )}
      keyExtractor={(item, index) => item.toString()}
    />
  </View>

Code for recalculateCategory:

const recalculateCategory = (rowData) => {
  setSelectedCategory(rowData);
  getCollection();
};

code for getCollection:

const getCollection = async() => {
    setIsLoading(true);
    const index = 1;
    const getThoughtsOneCategory = Firebase.functions().httpsCallable('getThoughtsOneCategory');
    await getThoughtsOneCategory({
      index,
      category: selectedCategory,
    }).then((result) => {
      setThoughts(result.data);
      setIsLoading(false);
    }).catch((err) => {
      console.log(err);
    });
  };

How it works is: if you want to see options posts, you click options, and it renders the data accordingly.

I am running into an issue.

  1. We are on "STOCKS"

添加

  1. Click on "OPTIONS" [Notice the data is the same as "STOCKS"]

在此处输入图像描述

  1. Click on "OPTIONS" again, and we get the correct data

在此处输入图像描述

How can I fix this requirement to double click on a menu category? Thanks

Instead of calling getCollection directly, you could use useEffect to call it whenever the category changes.

Something like:

useEffect(() => {
  getCollection();
},[selectedCategory])

And then your recalculateCategory would just look like:

const recalculateCategory = (rowData) => {
  setSelectedCategory(rowData);
};

useEffect runs whenever the parameters in the second argument change. You may need to adjust them to fit your use case, but selectedCategory would definitely be in there.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM