0

When I run the app, the error message shows that TypeError: undefined is not an object (evaluating '_useContext.state')

Here is my App.js:

import React from 'react'
import { StatusBar } from 'expo-status-bar';
import { useState, useEffect, useContext } from 'react';
import { StyleSheet, Text, View } from 'react-native';
import { Context as ActivitiesContext, Provider } from "./context/ActivitiesContext";

const App = () => {

  const { state, getActivity } = useContext(ActivitiesContext);

  useEffect(() => {
    getActivity()
  }, []);

  return (
    <View style={styles.container}>
      <Text>Open App.js to start working on your file</Text>
      <StatusBar style="auto" />
    </View>
  )
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#fff',
    alignItems: 'center',
    justifyContent: 'center',
  },
});

export default App

Here is my ActivitiesContext.js:

import createDataContext from "./CreateDataContext";

const getActivity = () => {
  return console.log("hi");
};

export const { Provider, Context } = createDataContext(
  {
    getActivity,
  }
);

Here is my CreateDataContext.js

import React, { useReducer } from 'react';

export default (reducer, action, defaultValue) => {
    const Context = React.createContext();

    const Provider = ({ children }) => {
        const [state, dispatch] = useReducer(reducer, defaultValue);

        const boundActions = {};

        for (let key in action) {
            boundActions[key] = action[key](dispatch);
        }

        return (
            <Context.Provider value={{ state, ...boundActions }}>
                {children}
            </Context.Provider>
        )
    };

    return { Context: Context, Provider: Provider };
};

I am expecting that the console.log("hi") from the function getActivity be passed to the App.js and console log "hi".

There also is the Provider, what is its purpose and how do I use it? I think that's what I am missing.

1 Answer 1

2
  1. Create context
  2. Use Provider to pass a value by wrapping an component to provide access for components deeper in the tree
  3. Use useContext to access the value from any of the components
const ThemeContext = React.createContext(); // 1.

const App = () => {
  // 2.
  return <ThemeContext.Provider value={{color: 'black', getColor: () => 'red'}}> 
      <MyComponet />
    </ThemeContext.Provider>
}

const MyComponet = () => {
  return (
    <View>
      <MyButton />
    </View>
  );
}

const MyButton = () => {
  const theme = useContext(ThemeContext) // 3.
 
  return <Button title="Button" color={theme.getColor()}/>;
}

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.