Search code examples
react-nativereact-native-flatlistasyncstorage

React Native FlatList renders data character by character


I have an array of objects like this:

[
  {"name":"XYZ","price":100,"instock":true},
  {"name":"OTR","price":945,"instock":true},
  {"name":"SLG","price":343,"instock":true}
]

The Flatlist renderItem displays it's each characters individually like this Output screenshot

My code is this

<View>
      {cartItems !== [] && (
        <FlatList
          data={cartItems}
          renderItem={({item}) => (
            <View>
              <Text>{item}</Text>
            </View>
          )}
          keyExtractor={(item, index) => index.toString()}
        />
      )}
    </View>

I also tried this renderItem={({item: {name, price}}) => ()} and tried to print, it didn't display anything and when I logged it to console both of them were undefined

<View>
          {cartItems !== [] && (
            <FlatList
              data={[cartItems]}
              renderItem={({item}) => (
                <View>
                  <Text>{item}</Text>
                </View>
              )}
              keyExtractor={(item, index) => index.toString()}
            />
          )}
        </View>

I also distructured the

But it rendered like this

[{"name":"XYZ","price":100,"instock":true},
 {"name":"OTR","price":945,"instock":true},
 {"name":"SLG","price":343,"instock":true}]

Here is the complete code

const ManageOrders = () => {


const [cartItems, setCartItems] = useState([]);

  const getItem = async () => {
    try {
      const item = await AsyncStorage.getItem('CartItem');
      // const items = JSON.parse(item); //This gave me error
      setCartItems(item);
    } catch (error) {
      console.log(error);
    }
  };

  useEffect(() => {
    getItem();
  }, []);

//   const data = JSON.parse(cartItems) //This gave me error
  return (
    <>
      <SafeAreaView style={styles.safeAreaView1} />
      <SafeAreaView style={styles.safeAreaView2}>
        <View>
          {cartItems !== [] && (
            <FlatList
              data={cartItems}
              renderItem={({item}) => (
                <View>
                  <Text>{item}</Text>
                </View>
              )}
              keyExtractor={(item, index) => index.toString()}
            />
          )}
        </View>
      </SafeAreaView>
    </>
  );
};

export default ManageOrders;

Note: The data cartItems I got it from asyncstorage AsyncStorage.getItem("CartItems") Can anyone help me with this please??


Solution

  • For me, the issue is I am not converting my API in JSON object when saving in REDUX.

    let itemList = JSON.parse(response.data.response.dataList)
    

    I did this and the error gone.