skip to Main Content

After adding the item to the array.it is not show means not render.

i am try myself but no success

my code It below you can run it online

import React,{useState,useEffect} from 'react';
import { StyleSheet, Text, View,TouchableOpacity,ScrollView} from 'react-native';
  

export default function App({navigation}) {
   const [dummyarray, setDummyarray] = useState([{id:1, product:"pendrive"}]);

async function addiem(){
dummyarray.push({id:2, product:"mobile phone"})
}

   return (
       <View  >
 <ScrollView>    

{dummyarray.map((item,idx) => (
            <View key={idx} style={{  backgroundColor: 'white'}}>
       <Text>{item.product}</Text>                
            </View>
    ))}


<TouchableOpacity onPress={()=>addiem()}><Text>Clear all orders</Text>
</TouchableOpacity>
 </ScrollView>
   </View>
    
  );
}

2

Answers


  1. React change detection works on immutability and by dummyarray.push(...) you are mutating the array so React cannot register the change. You have to use the setter you get from useState and copy the array in order to not mutate it. Like this:

    setDummyArray(prevArr => [...prevArr, {id:2, product:"mobile phone"}])

    Login or Signup to reply.
  2. async function addiem(){
       dummyarray.push({id:2, product:"mobile phone"})
     }
    

    This is wrong, you can’t update a state like this !
    You can use for example ... spread syntax

    function addiem(){
      setDummyarray.push(current => [...current, {id:2, product:"mobile phone"}])
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search