Transferring State Between Components in React Native

Just starting out with React Native.

I have a common use case where I'm working with React Navigation and have 4 different Tabs. In the first Tab, I have a FlatList from which I want to select Favorites. These Favorites should then be displayed in another Tab. That's all for now.

The issue I'm facing is figuring out how to pass the favorites variable, declared in the state of the first tab, to the other Tab. My approach might be completely wrong as well...

First Tab/Screen:

import React, {Component} from 'react';
import { FlatList, Text, View, ScrollView, Image, TouchableHighlight} from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons'

export default class HomeScreen extends Component {

  state = {
    data: [],
    favourites: []
  };

  //Function called when the Heart Button is clicked, adding the List Element to the State
  addFav = item => {
    this.setState((prevState) => ({'favourites': prevState.favourites+item.title+' '}))
    alert(item.title)
  }

  componentWillMount() {
    this.fetchData();
  }

  //Fetching data from the API
  fetchData = async () => {
    const response = await fetch("http://192.168.1.19:8080/v1/api/event");
    const json = await response.json();
    this.setState({ data: json});
  };

  render() {
    return <FlatList
          ItemSeparatorComponent={() =>
            <View
              style={{ height: 1, width: '100%', backgroundColor: 'lightgray' }}
            />
          }
          data={this.state.data}
          keyExtractor={(item => item.title)}
          renderItem={({ item }) =>
            <ScrollView>
              <Image style={{alignSelf:'stretch', width:undefined, height:undefined, flex : 1, borderRadius:10}} source = {require('../img/landscape.jpeg')}/>
              <TouchableHighlight onPress={()=>this.openEvent(item)}>
                <View style={{flex: 1, flexDirection:'row', padding: 5}}>
                  <View style={{flex: 1}}>
                    <Text style={{fontSize:15, textAlign:'center', padding: 2}}>{this.timeConverterMonth(item.time)}</Text>
                    <Text style={{fontSize:15, textAlign:'center', padding: 2}}>{this.timeConverterDay(item.time)}</Text>
                  </View>
                  <View style={{flex: 4}}>
                    <Text style={{fontSize:15, padding: 2}}>{item.title}</Text>
                    <Text style={{fontSize:10, padding: 2}}>{item.locShort}</Text>
                  </View>
//Function call here
                  <TouchableHighlight 
                    style={{flex: 2}} 
                    onPress={() => this.addFav(item)}
                  >
                    <Icon name="ios-heart-empty" size={24} style={{alignSelf: 'center', padding: 10}}/>
                  </TouchableHighlight>
                </View>
              </TouchableHighlight>
//State check
              <Text>{this.state.favourites}</Text>
            </ScrollView>}
        />;
  }
}

Second Tab/Screen:

import React, {Component} from 'react';
import {Text} from 'react-native';

export default class FavouritesScreen extends Component {

  constructor(props){
    super(props)
  }

  render(){
//Displaying favorites Array from HomeScreen State
    return <Text>{this.props.favourites}</Text>;
  }
}

I'm not surprised it's not working, as the Screens are not in a Parent/Child relationship.

What I want to do in the Second Tab is something like

HomeScreen.state.favourites

Thanks.

Answer №1

Your situation is quite common and something I have personally encountered before. In my case, it involved passing a 'shared state' between different components within the application.

Typically, components have their own local state which can be passed down to child components through props, as you mentioned. However, complications arise when trying to access this state in a separate component. This is where implementing a global state comes into play.

You might want to explore using Redux for managing state in your application. Check out https://redux.js.org/introduction/getting-started for more information on getting started with Redux.

Redux acts as a predictable state container for JavaScript applications, enabling consistent behavior across various environments and facilitating easier testing. It also offers helpful developer tools like live code editing and a time-traveling debugger.

By utilizing Redux, you'll establish a global state accessible to all components in your application. This empowers you to update states within one component and retrieve them in another, providing greater flexibility and efficiency.

Admittedly, learning Redux may seem challenging at first glance, especially with its initial complexity. Yet, as your application expands and incorporates more state management, you'll appreciate the benefits it brings.

Fortunately, there are abundant resources available for integrating Redux with React and React Native, ensuring plenty of tutorials to guide you through the process and enhance your current application.

Answer №2

If you find yourself needing to access state globally, state management libraries are a great solution. One popular option is Redux - where you can organize your favorites under a state called "HomeScreen" and easily use it across different screens in your app.

For more information on how to get started with Redux, check out this helpful article:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Acquiring Device Data in React-Native for iOS

Hello, I am currently attempting to retrieve device information from an iPad. I attempted to use the library found at https://github.com/rebeccahughes/react-native-device-info, however, it caused issues after performing a pod install. My main goal is to ob ...

Struggling with React Native and WebSocket integration issues

I've heard some concerns about Socket.io not functioning properly in React Native, so I opted to utilize plain WebSocket instead. Setting up a WebSocket server with node.js was relatively straightforward for me. While all my attempts were successful ...

Is it possible to utilize a single MobX store across two distinct components within a React Native application?

I am working on a module that includes a topTabNavigator wrapped with mobx provider using the store: export class ModuleTeam extends Component { render() { return ( <Provider store={store}> <TopTabNavigator /> </Pr ...

When the App is opened, Firestore triggers a function to run, and then again after any changes

I am looking to activate this function when the App is launched, and then whenever there is an update in my firestore data. export const getDuettsPlayer1 = (setDuetts) => { duettsRef.where("player1", "==", firebase.auth().currentUs ...

MySQL database encountered an error attempting to retrieve a frame for an index that is out of range (React Native)

Recently, I started my journey into learning react-native through instructional videos. However, the videos referenced the use of ListView, which is set to be deprecated and removed soon. After researching, it became clear that FlatList is the recommended ...

Issue: The module is not compatible with the "node" engine. It requires version ">= 14.20.0" but is receiving "14.17.4"

In the midst of working on a challenging branch, I struggled to organize my dependencies. However, after lots of effort, I finally managed to get everything up and running smoothly, with my GitLab pipelines passing successfully. Just so you know, the proje ...

If the Request does not recognize the OAuth key, generate a fresh new key

I am working with a React Native Frontend and an Express.js backend. The backend makes calls to a 3rd party API, which requires providing an OAuth key for the user that expires every 2 hours. Occasionally, when calling the API, I receive a 400 error indi ...

Effortlessly transferring images using Axios in Node.js: A guide

Previously, I utilized ApiSauce to send listings from my React Native application to a Node.js server with Multer. I made the switch to Axios, and everything went smoothly except for the image uploading component. export const add = (listing, onUploadPro ...

Unable to establish connection between React Native Socket.IO and a Node.js server

As I work on developing a React Native Expo app that requires real-time communication using socket.io, my Node.js server is up and running on localhost. Here's the code snippet: In React Native - home.js import { io } from "socket.io-client" ...

Issues with peer dependencies arise during the installation of npm packages

Seeking help with resolving the following errors: npm ERR! code ERESOLVE npm ERR! ERESOLVE unable to resolve dependency tree npm ERR! npm ERR! While resolving: x npm ERR! Found: <a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="1 ...

Getting started with React Native project

Just dipping my toes into the world of React Native and looking for recommendations on the best starter kit/generator to kickstart my projects. Tried out "create-react-native-app" already, but curious if there are any other generators or kits out there tha ...

Retrieve highlighted text along with its corresponding tag in ReactJS

my <span class="highlight">highlighted</span> word The text above is showing an example including HTML tags. However, when using window.getSelection(), only the text "my highlighted word" is returned without the surrounding <span& ...

Review the Drawer Item's Render Method

I have been using react-native with expo and following a specific guide closely: Is there an alternative way to implement this without the use of icons at the moment? Upon compiling, I encountered an error regarding the Render Method of DrawerItem. I&apo ...

I'm observing that my screen component is rendering twice when I implement multiple useFocusEffects - what could be causing

I have encountered an issue while using two useFocusEffect() hooks (specifically from the react-navigation-v6 library). In the code snippet below, when the screen is in focus, it gets rendered twice instead of just once as expected. The console.log() sta ...

Place the Drawer element at the bottom of the menu

Is there a way to position the menu point at the bottom of the screen? It would be great if we could easily customize the style of the navigation options for each element. Check out my App Navigator below: const AppNavigator = createDrawerNavigator( ...

Mastering the organization of dependency arrays within the useEffect hook

Let's say I have two variables called varA and varB. I want to perform an action on varA only when varB changes. To achieve this, I can use the following code snippet... useEffect(()=> { DO SOMETHING TO varA; }, [varB]) If I follow this approach ...

What could be causing the double invocation of render() in ReactNative?

I'm currently working on an app with a single screen displaying a map centered on the user's current coordinates. In my code below, I've set the latitude and longitude to null in the state of the App component. Using the componentDidMount() ...

When the state value is updated, the react prop value also changes accordingly

I am facing an issue with a React component where I pass a single prop to a child component: const Parent: FunctionComponent = ({ route }) => { const { routeProp } = route.params; const { passThisProp } = routeProp; return ( <Chi ...

excessive memory usage in a simple react-native application

My experience with creating my first react native app has been more challenging than I initially expected. I'm having trouble understanding what I might be doing wrong. Initially, the app is simple, fetching data through Redux. componentWillMount() ...

React Native: Encounter a build error due to an undefined issue when building the JavaScript

I successfully set up react native by running: expo init AwesomeProject Initially, everything was working smoothly until I decided to install a new NPM package. I managed to create three pages without any issues, but encountered warnings after installing ...