skip to Main Content

I am trying to set up useContext in my react native app to make some data universally available, but something in my set up is wrong, as the value I’m passing down ends up being undefined in a component I’m trying to consume the data in.

First off, I have this – notice I am passing 245 down as a test:

import React from 'react';

const DataContext = React.createContext();

export const DataProvider = ({ children }) => {
  return <DataContext.Provider value={245}>{children}</DataContext.Provider>;
};

Then I wrap my App.js file in that provider like so:

import Navigator from './src/navigation/Navigator';
import { DataProvider } from './src/context/DataContext';

export default App = (props) => {
  return (
    <DataProvider>
      <Navigator />
    </DataProvider>
  );
};

And then in the component down the tree I try to consume it like so

import React, { useContext } from 'react';
import { View, Text, FlatList, StyleSheet } from 'react-native';
import { ScrollView } from 'react-native-virtualized-view';
import { getShortTeamName } from './../utils';
import TOP_GOAL_SCORERS from '../data/goalScorers';
import { DataProvider } from '../context/DataContext';

const Item = ({ name, team, goals, value }) => (
  <View style={styles.item}>
    <Text style={styles.name}>{name}</Text>
    <Text style={styles.team} onPress={() => navigation.navigate('Team')}>
      {team}
    </Text>
    <Text style={styles.goals}>{goals}</Text>
  </View>
);

const GoalScorersScreen = () => {
  const value = useContext(DataProvider);
  console.log('value 20: ', value); // this is undefined
  return (
    <ScrollView style={styles.container}>
      <FlatList
        data={TOP_GOAL_SCORERS}
        renderItem={({ item }) => (
          <Item name={item.name} value={value} goals={item.goals} team={getShortTeamName(item.team)} />
        )}
        keyExtractor={(item) => item.name}
      />
    </ScrollView>
  );
};

What am I missing with this setup/implementation?

2

Answers


  1. You should pass your created context into the useContext hook, not the DataProvider

    import { DataContext } from '../context/DataContext';
    ...
    
    const GoalScorersScreen = () => {
      const value = useContext(DataContext);
      ...
    };
    
    Login or Signup to reply.
  2. Make sure you export the context object(DataContext in this case):

    import React from 'react';
    
    export const DataContext = React.createContext();
    
    export const DataProvider = ({ children }) => {
      return <DataContext.Provider value={245}>{children}</DataContext.Provider>;
    };
    

    And then pass DataContext to useContext instead of DataProvider:

      const value = useContext(DataContext);
    

    After that, it should work for you.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search