React Native Context API returns undefined for state

Viewed 30

All I am trying to do is to welcome the user on the screen. Here is the code.

context.js

import React, {Component} from "react";

const MyContext = React.createContext();
class MyProvider extends Component {
      this.state = {
            isAuthenticated: false,
            user: {
                    name: "YYY",
                    email: "yyy@gmail.com"
                  }
      };

  render() {
      console.log(this.state)
      return (
           <MyContext.Provider value = {this.state}>
              {this.props.children}
          </MyContext.Provider>
      );
  };

};
export {MyContext, MyProvider};

App.js Code

import React from 'react';
import {StyleSheet, Text } from 'react-native';
import {MyContext, MyProvider} from './src/context/context';

function App() {
  return (
      <MyProvider>
          <Header />
      </MyProvider>
  )
}

export default class Header extends React.Component {
  render() {
    return (
      <MyContext.Consumer>
        { value => { console.log(value);
                     return (
                          <Text style={styles.text}>
                              Welcome {value}
                          </Text>)
                   }
        }
      </MyContext.Consumer>
    )
  }
}

const styles = StyleSheet.create({
  text: {
    fontSize: 24,
    alignSelf: 'center',
    alignContent:'center',
  },

});

The App simply prints Welcome on the screen. I would like it to print the entire state contents like isAuthenticate, name & email. What am I doing wrong?

1 Answers

value is an object so you'll need to access the individual props inside it:Welcome {value?.user?.name} or replace Welcome {value} with Welcome {JSON.stringify(value)}

Related