0

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;

1 Answer 1

2

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.

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

2 Comments

or maybe JSON.stringify(storedEvents)
vindev Thank you very much. I got it! @Shahriar Thank you too!

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.