getting empty array on first function call stack navigation

29 Views Asked by At
const showdata = ()=> {
  setdata([...data, {
    user: username,
    email: email,
    password: password,
  }])

  navigation.navigate('home', {
    showdata: data,
  });
};

home screen

import { StyleSheet, Text, View } from 'react-native'
import React from 'react'
import { FlatList } from 'react-native-gesture-handler';

const Home = ({ navigation, route }: any) => {
  const showdata = route.params.showdata;
  console.log(showdata)
     
  return (
    <View>
      <FlatList
        data={showdata}
        renderItem={({item}:any)=>{
          return (
            <View style={{margin:20 ,}}>
              <Text>UserName:   {item.user}</Text>
              <Text>Email: {item.email}</Text>
              <Text>password:  {item.password}</Text>
            </View>;`your text`
          )}}
      />
    </View>
  );
}
export default Home;

This function state variable is assigned data but on first click it gives empty array i want to set data and render it on first click

I have 3 useState and i am saving data in an array of object data from setdata

1

There are 1 best solutions below

2
Rakhil On

Store the variable in a state when route.params.showdata is available. This can be done using useEffect

import React, { useEffect, useState } from 'react';
import { View, Text, FlatList } from 'react-native';

const Home = ({ navigation, route }: any) => {
  const [data, setData] = useState([]); // State to store showdata

  // Update the data state when route.params.showdata changes
  useEffect(() => {
    setData(route.params.showdata);
  }, [route.params.showdata]);

  return (
    <View>
      <FlatList
        data={data}
        renderItem={({ item }: any) => {
          return (
            <View style={{ margin: 20 }}>
              <Text>UserName: {item.user}</Text>
              <Text>Email: {item.email}</Text>
              <Text>password: {item.password}</Text>
            </View>
          );
        }}
      />
    </View>
  );
};

export default Home;