0

I have a button where it gets the account number that was entered and it uses that number to fetch the data. The function then calls another function called goToHome and I set the data to setJsonWineData and pass it to navigation.navigate('Home',{wineData:jsonWineData}) and then it goes to the Home page. When I try to console log the data that I passed to the Home page, it's empty. I'm not sure why it's coming back empty when I pass it to the other page.

This is the button that calls logIn function:


    <TouchableOpacity style={{marginRight:20,fontSize:30}}>
         <Button
             title="Log in"
             onPress={() => logIn(userId)}
         /> 
    </TouchableOpacity>

This is the logIn function where it calls goToHome:

function logIn(userId){

   
        fetch('https://somesite.com/wine/php/file.php?action=get_wine_list&winery_id=' + userId)
            .then((response) => response.json())
            .then((data) => {
                
                goToHome(data);
              
            })
            .catch((error) => {
                alert("Error. Make sure ID is correct and that you have an internet connection and try again.")  
            });
}

This is the goToHome function:

function goToHome(jsonData){
        
        setJsonWineData(jsonData)
           
        navigation.navigate('Home',{wineData:jsonWineData})
    
    }

This is the Home page where I try to call wineData:


const Home = ({route,navigation}) => {

 const { wineData } = route.params;
 console.log("wines: " + wineData);
}

Here is all the code:

import 'react-native-gesture-handler';
import React, {useState, useEffect, useRef} from 'react';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator, HeaderBackButton } from '@react-navigation/stack';

import {
    SafeAreaView,
    StyleSheet,
    ScrollView,
    View,
    Text,
    StatusBar,
    ImageBackground,
    Image,
    TextInput,
    Button,
    TouchableNativeFeedback,
    TouchableWithoutFeedback,
    TouchableOpacity,
    Dimensions,
    Modal,
    Pressable,
    PanResponder,
    FlatList
  } from 'react-native';
  
  import { Immersive } from 'react-native-immersive';
  
  
  import {
    Header,
    LearnMoreLinks,
    Colors,
    DebugInstructions,
    ReloadInstructions,
  } from 'react-native/Libraries/NewAppScreen';



 

const LoginScreen = ({navigation}) => {

    const [userId, setUserId] = useState(''); 

    const [jsonWineData, setJsonWineData] = useState([]); 

    function goToHome(jsonData){
        
        setJsonWineData(jsonData)
           
        navigation.navigate('Home',{wineData:jsonWineData})
    
    }

    function logIn(userId){

   
        fetch('https://somesite.com/wine/php/file.php?action=get_wine_list&winery_id=' + userId)
            .then((response) => response.json())
            .then((data) => {
          
                
                goToHome(data);

              
            })
            .catch((error) => {
                alert("Error. Make sure ID is correct and that you have an internet connection and try again.")  
            });
         
    }    
    

      
   
    return(
    
      <View style={{alignItems:'center'}}>
            <Text style={{textAlign:'center', color:'white', fontSize:40, marginTop:40}}>VinePress</Text>

            <TextInput
                style={{color:'black', borderWidth:1, width:200,
            marginTop:40, marginBottom:50, borderColor:'white', backgroundColor:"white", textAlign:'center', fontSize:30}}
                placeholder="User ID"
                keyboardType="number-pad"
                placeholderTextColor="#adadad"
                onChangeText={userId=> setUserId(userId)}
                value={userId}
            />


            <View style={{flexDirection:'row', margin:20}}> 
                
                <TouchableOpacity style={{marginRight:20,fontSize:30}}>
                    <Button
                        title="Log in"
                        onPress={() => logIn(userId)}
                       
                    /> 
                </TouchableOpacity>


                <Button
                    title="Log Out"
               
                />            
            
            </View>
        
      </View>
     
    )
  }

  export default LoginScreen
  


oxxi
  • 452
  • 3
  • 11
  • 28
  • React state updates are asynchronous, so `jsonWineData` is still the value from the current render cycle, not the value you enqueued for the next render cycle. – Drew Reese Jun 13 '21 at 23:17
  • Why not just navigate with the `jsonData` value directly? You're navigating from the "login" page so the state update is rather moot, right? – Drew Reese Jun 13 '21 at 23:24
  • I tried but it's still empty. I think I need to go back to the drawing board. I suck at coding. – oxxi Jun 13 '21 at 23:27
  • Is the `response` from the GET request what you expect it to be? Is `goToHome` called with the correct `data` value? – Drew Reese Jun 13 '21 at 23:31
  • I can console log jsonData within goToHome but I can't log jsonWineData so I guess I have to use something like useEffect to make this work. I thought it would work by calling goToHome after getting the response data – oxxi Jun 13 '21 at 23:39
  • Nono, just `navigation.navigate('Home', { wineData: jsonData });`, there's no need for the state update. – Drew Reese Jun 13 '21 at 23:44
  • Well that worked! I thought I tried that but I guess I missed it. Thank you. – oxxi Jun 14 '21 at 00:00

0 Answers0