Home > database >  React-native useContext get undefined
React-native useContext get undefined

Time:09-28

I try to use Context API in react native peoject, but I don't know why I get undefined.

Here is my code, also can run in codesandbox here.

import React, { useState, createContext, useContext } from "react";
import { Text, View } from "react-native";

const FakeContext = createContext();

const FakeProvider = (props) => {
  const [event, setEvent] = useState({ text: "Hello!", name: "molly" });

  return (
    <FakeContext.Provider value={event}>{props.children}</FakeContext.Provider>
  );
};

const App = () => {
  const storedEvents = useContext(FakeContext);
  console.log(storedEvents); //undefined
  return (
    <View>
      <FakeProvider>{/* <Text>{storedEvents}</Text> */}</FakeProvider>
      <View>
        <Text>LOGIN~~~~~</Text>
      </View>
    </View>
  );
};

export default App;

enter image description here

CodePudding user response:

You can access it in the fakeprovider child elements:

see below the new component- NewStore.

import React, { useState, createContext, useContext } from "react";
import { Text, View } from "react-native";

const FakeContext = createContext();

const FakeProvider = (props) => {
  const [event, setEvent] = useState({ text: "Hello!", name: "molly" });

  return (
    <FakeContext.Provider value={event}>{props.children}</FakeContext.Provider>
  );
};

const App = () => {
  const storedEvents = useContext(FakeContext);
  console.log(storedEvents); //undefined
  return (
    <View>
      <FakeProvider><NewStore />{/* <Text>{storedEvents}</Text> */}</FakeProvider>
      <View>
        <Text>LOGIN~~~~~</Text>
      </View>
    </View>
  );
};

const NewStore = () => {
  const storedEvents = useContext(FakeContext);
  console.log(storedEvents); 
  return <div>new store</div>;
}

export default App;
  • Related