0

one place I seem to be stuck is on is being able to populate an array of objects, which are used for a FlatList later on.

I get this data from my FireStore – for each document, it will push the objects into ‘const DATA = []’ But when I run the ‘getUsers()’ inside of UseEffect, it only updates ‘DATA’ inside of the method, it doesn’t update the global variable.

Im new to react native, so im probably missing something important within my structure. Thanks for any assistance tho!

enter image description here

I need the format of DATA to look like this example:

enter image description here

My Code:

const MainScreen = () => {


  const DATA = [];
  const navigation = useNavigation()
  const [selectedId, setSelectedId] = useState(null);
  const usersCollectionRef = collection(db, "Posts");
  const [Data, setData]= useState([]);

  LogBox.ignoreLogs(['Setting a timer']);
  LogBox.ignoreLogs(['AsyncStorage has been extracted']); 
  LogBox.ignoreAllLogs(true);

useEffect(() => {
 getUsers();
 console.log(DATA);
  }, []);


  const getUsers = async () => {
    const data = await getDocs(usersCollectionRef);
    data.forEach(doc =>{
    const dataG = (doc.id, "=>", doc.data());
    DATA.push({
      id: doc.id, 
      title: dataG.status +" "+ dataG.Type, 
      status: dataG.status, 
      location: dataG.Location, 
      type: dataG.Type, 
      injured: dataG.Injured, 
      collar: dataG.Collar, 
      color: dataG.Colour, 
      username: dataG.username, 
      description: dataG.Description,
      imagesrc: dataG.picture });
    })
  
  };

  
  
  const Item = ({ item, onPress, backgroundColor, textColor }) => (
    <View style={styles.ContentBox}>

    <TouchableOpacity onPress={onPress} style={[styles.item, backgroundColor]}>
      <Text style={[styles.title, textColor]}>{item.title}</Text>
      <Text style={styles.ContentText}>By: {item.username}</Text>
    </TouchableOpacity>

    <Image source = {{uri: item.imagesrc}}
   style = {{ width: 200, height: 200, alignSelf:'center' }}/>
   
    <Text style={styles.ContentText}>Animal: {item.type}</Text>
    <Text style={styles.ContentText}>Location: {item.location}</Text>
    <Text style={styles.ContentText}>Injured: {item.injured}</Text>
    <Text style={styles.ContentText}>Colour: {item.color}</Text>
    <Text style={styles.ContentText}>Has a Collar: {item.collar}</Text>
    <Text style={styles.ContentText}>Description: {item.description}</Text>
    

    </View>
  );

  const renderItem = ({ item }) => {
    const backgroundColor = item.status === "lost" ? '#b80909' : '#098231';
    const color = item.id === selectedId ? 'white' : 'white';

    return (

      <Item
        item={item}
        onPress={() => setSelectedId(item.id)}
        backgroundColor={{ backgroundColor }}
        textColor={{ color }}
      />
    );
  };

const PostScreen = () =>{
  navigation.navigate('PostScreen');
}



  return (
    
    <SafeAreaView style={styles.container}>


    <View style={styles.MainFeed}>
 
    <FlatList
        data={DATA}
        renderItem={renderItem}
        keyExtractor={item => item.id}
        extraData={selectedId}
      />
    

    </View>
)
  • You can't push to a `const` like that within a React component. Instead, you'll want to use a `useState`. See https://stackoverflow.com/questions/54676966/push-method-in-react-hooks-usestate – jnpdx Mar 09 '22 at 06:42
  • @jnpdx Yes, ive tried to push it into a useState variable, which was called const [Data, setData] = useState([]); But the format isnt correct.. It doesnt map correctly. – GarlicBread Mar 09 '22 at 06:44
  • That's not what you're using -- you also have a `const DATA` -- the two are not the same -- capitalization matters. Plus, you're just trying to use `DATA.push`, not `setData` -- check that link I sent -- it has specific instructions. – jnpdx Mar 09 '22 at 06:45

2 Answers2

1

instead of pushing data in a variable and then updating the state, you can do it like this directly -

 setData([...Data,{
      id: doc.id, 
      title: dataG.status +" "+ dataG.Type, 
      status: dataG.status, 
      location: dataG.Location, 
      type: dataG.Type, 
      injured: dataG.Injured, 
      collar: dataG.Collar, 
      color: dataG.Colour, 
      username: dataG.username, 
      description: dataG.Description,
      imagesrc: dataG.picture
    }])
this.arjun
  • 330
  • 1
  • 4
0

The answer is that after doing DATA.push(...), I needed to setData(DATA).

enter image description here

ouflak
  • 2,458
  • 10
  • 44
  • 49
  • Welcome to StackOverflow! Please avoid posting images of code (obviously unless that is central to the question/answer), instead posting the actual code in your posts. – ouflak Mar 09 '22 at 13:59