Saeedr
Saeedr

Reputation: 19

Pass a variable from one file to another in React Native

I'm building a front end app on React Native. One file (screen) is generating a Token using the following code

fetch("http://192.168.1.11:8080/api/login", {
                method: 'POST',
                body: JSON.stringify({
                    username: 'user'
                }),
                headers: {
                    'Accept': 'application/json',
                    'Content-Type': 'application/json',
                }
        
        
            }).then((response) => response.json())
      .then((json) => {
        this.setState({ JwToken: json.token });
      }).then((json) =>this.props.navigation.navigate('Home')/)
      .catch((error) => console.error(error))
      .finally(() => {
        this.setState({ isLoading: false });
      });

In another file I must use that token for verification

fetch('http://192.168.1.11:8080/api/books', {
  method: 'POST',
  headers: {
    Accept: 'application/json',
    'Content-Type': 'application/json',
    'Authorization': 'Bearer ' + JwToken

  },
  body: JSON.stringify({
    title: 'new book',
    price: 4
  })
});

I had no idea how to pass the token between the two files.

Upvotes: 0

Views: 513

Answers (1)

derringa
derringa

Reputation: 109

This is something I've referenced before from the React Navigation Docs that seems to fit your needs.

function HomeScreen({ navigation }) {
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Home Screen</Text>
      <Button
        title="Go to Details"
        onPress={() => {
          /* 1. Navigate to the Details route with params */
          navigation.navigate('Details', {
            itemId: 86,
            otherParam: 'anything you want here',
          });
        }}
      />
    </View>
  );
}

function DetailsScreen({ route, navigation }) {
  /* 2. Get the param */
  const { itemId } = route.params;
  const { otherParam } = route.params;
  return (
    <View style={{ flex: 1, alignItems: 'center', justifyContent: 'center' }}>
      <Text>Details Screen</Text>
      <Text>itemId: {JSON.stringify(itemId)}</Text>
      <Text>otherParam: {JSON.stringify(otherParam)}</Text>
      <Button
        title="Go to Details... again"
        onPress={() =>
          navigation.push('Details', {
            itemId: Math.floor(Math.random() * 100),
          })
        }
      />
      <Button title="Go to Home" onPress={() => navigation.navigate('Home')} />
      <Button title="Go back" onPress={() => navigation.goBack()} />
    </View>
  );
}

Upvotes: 1

Related Questions