1
import React from 'react';

export function useAuth() {
  const [name, setName] = React.useState('Sa');

  return {name, setName};
}
import {createContext} from 'react';

export const UserContext = createContext();


import React from 'react';
import {useAuth} from './userHook';
import {UserContext} from './userContext';
import Pagesd from './pagesd';

export default function () {
  const {name} = useAuth();
  return (
    <UserContext.Provider value={name}>
      <Pagesd />
    </UserContext.Provider>
  );
}
import React from 'react';
import {View, Text} from 'react-native';
import {UserContext} from './userContext';

function Pagesd() {
  const {name} = React.useContext(UserContext);
  return (
    <View>
      <Text>{name}</Text>
    </View>
  );
}
export default Pagesd;

I expected the function useAuth to see Sa Pagesd () typed where am I doing wrong

I want to do the case management, but the name comes in the app js, but I cannot access the children.

1 Answers1

0

The code shown so far is correct, with one exception.

const {name} = React.useContext(UserContext);

The value name is being destructured from the return of useContext. This is fine if the value being given is an object, but I assume it's not.

<UserContext.Provider value={name}>

If name is not an object, but a string, then the destructure will not work, and name will be undefined.

To solve this you have two options:

  1. Do not destructure the name value
const name = React.useContent(UserContext);
  1. Pass the provider an object
<UserContext.Provider value={{name}}>

React uses curly braces {} to denote a JavaScript expression, whereas the inner curly braces is an object literal property value shorthand.

evolutionxbox
  • 3,932
  • 6
  • 34
  • 51