Home > Software engineering >  Cannot Pass State by React-native Context API
Cannot Pass State by React-native Context API

Time:09-28

I try to pass State and SetState by using useContext. But there someting strange: only one can pass to children compoenents. I want to pass {isLogin, setIsLogin, name}, only name can show correctly like this:

also can run in codesandbox

codesandbox

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

const AppContext = createContext();

const AppProvider = (props) => {
  const [isLogin, setIsLogin] = useState(false);
  const [name, setName] = useState("molly");

  return (
    <AppContext.Provider value={(isLogin, setIsLogin, name)}>
      {props.children}
    </AppContext.Provider>
  );
};

const App = () => {
  return (
    <AppProvider>
      <Home />
    </AppProvider>
  );
};
const Home = () => {
  const storedEvents = useContext(AppContext);

  console.log("storedEvents", storedEvents);

  const login = () => {
    storedEvents.setIsLogin(true);
  };
  if (!storedEvents.isLogin) {
    return (
      <View>
        <View>
          <Text>{storedEvents}</Text>
        </View>
        <Button title="login" onPress={() => login()} />
      </View>
    );
  }
  return (
    <View>
      <Text>I am Login.</Text>
    </View>
  );
};

export default App;

CodePudding user response:

You can pass multiple values as the JSON object, so your AppProvider should look something like this.

const AppProvider = (props) => {
  const [isLogin, setIsLogin] = useState(false);
  const [name, setName] = useState("molly");

  return (
    <AppContext.Provider value={{isLogin, name, setIsLogin}}>
      {props.children}
    </AppContext.Provider>
  );
};

Notice the change value={{isLogin, name, setIsLogin}} instead of value={(isLogin, name, setIsLogin)}


There's another issue in the Home component which will give render error. You are trying to display storedEvents object which is not allowed. So change it to text string like Not logged in or something.

  • Related