Using useContext showing an error: Undefined is not an object - javascript

I am attempting to write a sign in screen within React-Native, but I got the error following:
enter image description here
my SignInScreen code:
import React from 'react';
import {
View,
Text,
TouchableOpacity,
TextInput,
Platform,
StyleSheet ,
StatusBar,
Alert
} from 'react-native';
import * as Animatable from 'react-native-animatable';
import LinearGradient from 'react-native-linear-gradient';
import FontAwesome from 'react-native-vector-icons/FontAwesome';
import Feather from 'react-native-vector-icons/Feather';
import { useTheme } from 'react-native-paper';
import { AuthContext } from '../components/context';
import Users from '../model/users';
const SignInScreen = ({navigation}) => {
const [data, setData] = React.useState({
username: '',
password: '',
check_textInputChange: false,
secureTextEntry: true,
isValidUser: true,
isValidPassword: true,
});
const { colors } = useTheme();
const { signIn } = React.useContext(AuthContext);
const textInputChange = (val) => {
if( val.trim().length >= 4 ) {
setData({
...data,
username: val,
check_textInputChange: true,
isValidUser: true
});
} else {
setData({
...data,
username: val,
check_textInputChange: false,
isValidUser: false
});
}
}
my context.js:
import React from 'react';
export const AuthContext = React.createContext();
my app.js:
import * as React from 'react';
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
import SignInScreen from "./screens/SignInScreen";
export default function App() {
return <SignInScreen/>;
}
I am just wondering is it missing some components and how do I fix it? And I already tried to reinstall my packages.

You need to provide the signIn function to the context somewhere. Typically, this is achieved with a context provider. You can find some more information in the docs. It may look something like this:
import React from 'react';
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
import SignInScreen from "./screens/SignInScreen";
export const AuthContext = React.createContext();
const signIn = () => {
// ... sign into an account or something
}
export default function App() {
return (
<AuthContext.Provider value={{signIn}}>
<SignInScreen/>
</AuthContext.Provider>
)
}
However, it may be worth reading through the docs and considering why you are using context here as this is not often how a sign-in function works in React/React-Native.

Related

how to pass 'web socket (Socket.Io) to certain screens (not a chat app)

i am having trouble passing Socket.Io socket to certain screens in my react native app, I want to share the socket with the navigation (like a prop I think I am not sure). Does someone have any suggestions on how to do it? I tried to use this approach(https://dev.to/bravemaster619/how-to-use-socket-io-client-correctly-in-react-app-o65) on react native and it didn't work.
I am open to ideas and my main goal is to share the same socket with two pages after the signin/signup and to send a token to confirm the user when the socket is making the connection.
app.js-
import React from 'react';
import { createAppContainer, createSwitchNavigator } from 'react-navigation';
import { createStackNavigator } from 'react-navigation-stack';
import { createBottomTabNavigator } from 'react-navigation-tabs';
import { setNavigator } from './src/navigationRef';
import AccountScreen from './src/screens/AccountScreen';
import SigninScreen from './src/screens/SigninScreen';
import SignupScreen from './src/screens/SignupScreen';
import ProductDetailScreen from './src/screens/ProductDetailScreen';
import ProductListScreen from './src/screens/ProductListScreen';
import AddProductScreen from './src/screens/AddProductScreen';
import ResolveAuthScreen from './src/screens/ResolveAuthScreen';
import { Provider as AuthProvider } from './src/context/AuthContext';
import { Provider as ProductProvider } from './src/context/ProductDetailContext';
import { SocketContext, socket} from './src/context/SocketContext';
import { FontAwesome } from '#expo/vector-icons';
const PlnatListFlow = createStackNavigator({
ProductList:ProductListScreen,
ProductDetail: ProductDetailScreen,
});
PlnatListFlow.navigationOptions = {
title: 'ProductList',
tabBatIcone: <FontAwesome name="th-list" size={20} />,
};
const switchNavigator = createSwitchNavigator({
ResolveAuth: ResolveAuthScreen,
loginFlow: createStackNavigator({
Signup: SignupScreen,
Signin: SigninScreen,
}),
mainFlow: createBottomTabNavigator({
PlnatListFlow: PlnatListFlow,
AddProduct: AddProductScreen,
Account: AccountScreen,
}),
});
const App = createAppContainer(switchNavigator);
export default () => {
return (
<SocketContext.Provider value={socket}>
<ProductProvider>
<AuthProvider>
<App
ref={(navigator) => {
setNavigator(navigator);
}}
/>
</AuthProvider>
</ProductProvider>
</SocketContext.Provider>
);
};
SocketContext.js-
import React from 'react';
import io from "socket.io-client";
import {url} from '../api/Config';
export const socket = io(url, {
transports: ["websocket"],
// upgrade:false,
});
export const SocketContext = React.createContext();

React native app is not rendering the component

I am getting this error: error message
Not really sure what I did wrong because everything looks right with my code, at least if I missed something.
import React, { useState } from "react";
import Home from "./screens/home";
import { View } from "react-native";
import * as Font from "expo-font";
import { AppLoading } from "expo-app-loading";
const getFonts = () =>
Font.loadAsync({
"poppins-regular": require("./assets/fonts/Poppins-Regular.ttf"),
"poppins-bold": require("./assets/fonts/Poppins-Bold.ttf"),
});
export default function App() {
const [fontsLoaded, setFontsLoaded] = useState(false);
if (fontsLoaded) {
return <Home />;
} else {
return (
<AppLoading startAsync={getFonts} onFinish={() => setFontsLoaded(true)} />
);
}
}
Can you try changing
import { AppLoading } from "expo-app-loading";
to this:
import AppLoading from 'expo-app-loading';

redux not being connected to react native properly

Being a newbie to react native ,I am finding it difficult to connect my redux with react native and make it work. After javascript bundle finishes ,I see an error "can't read property type of undefined" or "could not find store in either the context or props of "connect".Either wrap the root component in a or explicitly pass "store" as prop.I don't see any of the console.log working except for reducer .
Here is the action that I am using
import {ADD_PLACE,DELETE_PLACE,DESELECT_PLACE,SELECT_PLACE} from './actiontypes';
export const addPLace =(placeName) =>{
console.log('addPLace is being dispatched now');
console.log('In addPLace reducer');
return{
type:ADD_PLACE,
payload:{
placeName:placeName
}
};
};
export const deletePlace =()=>{
return{
type:DELETE_PLACE
};
}
export const selectedPlace =(key) =>{
return{
type:SELECT_PLACE,
payload:{
placekey:key
}
};
};
export const deselectPlace =()=>{
return {
type:DESELECT_PLACE
};
};
Here is the reducer part
import {ADD_PLACE,DELETE_PLACE,SELECT_PLACE,DESELECT_PLACE} from '../actions/actiontypes';
import PlaceImage from "../../../src/assets/download.jpeg";
const INITIAL_STATE={
places:[],
selectedPlace:null
}
const reducer =(action,state=INITIAL_STATE) =>{
console.log('INside reducer');
console.log(action);
switch(action.type){
case ADD_PLACE:
return {
...state,
places:state.places.concat({
key:Math.random(),
name:action.payload.placeName,
image:placeImage
})
};
case DELETE_PLACE:
return{
...state,
places:state.places.filter(place =>{
return place.key !== state.selectedPlace.key;
}),
selectPlace:null
};
case SELECT_PLACE:
return{
...state,
selectedPlace:state.places.find(place=>{
return place.key ===action.payload.placekey;
})
};
case DESELECT_PLACE:
return{
...state,
selectPlace:null
};
default:
return state;
}
}
export default reducer;
Here is the App.js
import React, { Component } from "react";
//import { StyleSheet, Text, View, TextInput, Button } from "react-native";
import store from './src/store/reducers/index.js';
import {Provider} from 'react-redux';
//import {createStore} from 'redux';
//import {connect} from 'react-redux';
import Home from './Home.js';
export default class App extends React.Component {
render() {
console.log('inside App');
console.log(store);
return (
<Provider store={store}>
<Home />
</Provider>
);
}
}
Here is the Home.js
import React, { Component } from "react";
import { StyleSheet, Text, View, TextInput, Button } from "react-native";
//import ListItem from './src/components/ListItem';
import PlaceInput from "./src/components/PlaceInput";
import PlaceList from "./src/components/PlaceList";
//import PlaceImage from "./src/assets/download.jpeg";
import PlaceDetail from "./src/components/PlaceDetail";
//import configureStore from './src/store/reducers/index.js';
//import {Provider} from 'react-redux';
//import {createStore} from 'redux';
import {connect} from 'react-redux';
import {addPLace,deletePlace,selectedPlace,deselectPlace} from './src/store/actions';
//const store=configureStore();
class Home extends React.Component {
placeAddedHandler =val=>{
console.log('Val is ',val);
console.log(val);
this.props.onAddPlace(val);
};
placeSelectHandler =id=>{
console.log('id is');
this.props.onSelectPlace(id);
};
placeDeleteHandler =() =>{
console.log('inside delete handler');
this.props.onDeletePlace();
};
modelClosedHandler =() =>{
console.log('iinside close handler');
this.props.onDeslectPlace();
}
render() {
console.log('Inside render function');
return (
<View style={styles.container}>
<PlaceInput onPlaceAdded={this.placeAddedHandler}/>
<PlaceList places={this.props.places} onItemSelected={this.placeSelectHandler}/>
<PlaceDetail
selectedPlace={this.props.selectedPlace}
onItemDeleted={this.placeDeleteHandler}
onModalClosed={this.modelClosedHandler}
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
padding:30,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'flex-start',
},
});
const mapStateToProps=state => {
console.log('Inside mapStateToProps ');
console.log(state );
return {
places:state.places.places,
selectedPlace:state.places.selectPlace
};
}
const mapDispatchToProps = dispatch =>{
return {
onAddPlace:(name)=>dispatch(addPLace(name)),
onDeletePlace:()=>dispatch(deletePlace()),
onSelectPlace:(id)=>dispatch(selectedPlace(id)),
onDeslectPlace:()=>dispatch(deselectPlace())
};
}
export default connect(mapStateToProps,mapDispatchToProps)(Home);
Link to github repo of project at this moment
github link
Looks like you have made a small import/export error.
In your reducers/index.js you are exporting it as a non default value which you are trying to import as default value in App.js.
import store from './src/store/reducers/index.js';
should be
import {store} from './src/store/reducers/index.js';
Let me know if it works.

React-native:cannot read property 'navigate' of undefined

I'm getting below error when im trying to navigate to different screen from home screen. i defined initial loading screen in routes. From initial screen trying to navigate to different screen then getting below error.
this.props is returning just {}. Not really sure why.
login.component.js
import React, {Component} from 'react';
import {NavigationActions} from 'react-navigation';
import {
Platform,
StyleSheet,
Text,
View,
TextInput,
TouchableOpacity,
Touchable,
Image,
Button
} from 'react-native';
import { handleFbLogin } from '../../config/authConfig/';
class Login extends Component {
render () {
console.log("this.props")
console.log(this.props)
return (
<View style={{flex: 1,backgroundColor: '#37afa6'}}>
<Button
title="Go to Details"
onPress={() => this.props.navigation.navigate('setupProfile')}
/>
</View>
);
}
}
export default Login;
routes/index.js
import {StackNavigator} from 'react-navigation';
import Login from '../pages/Login.page';
import SetupProfile from '../pages/setupProfile.page';
const Config = {
navigation: {
login: {
screen: Login
},
setupProfile: {
screen: SetupProfile,
}
}
}
export default Config;
App.container.js
import React, {Component} from 'react';
import Login from './pages/Login.page';
import {connect} from 'react-redux';
import Router from './routes';
import {
Platform,
StyleSheet,
Text,
View,
TextInput
} from 'react-native';
class App extends Component {
render () {
return (
<Router />
);
}
}
export default App;
index.js(startup point):
import { AppRegistry } from 'react-native';
import { StackNavigator } from 'react-navigation';
import app from './app/index';
import Config from './app/routes/index';
export const AppNavigator = StackNavigator(Config.navigation,{initialRouteName : 'login'});
AppRegistry.registerComponent('BuddApp', () => AppNavigator);
export default app;
i'm able to load initalscreen after these changes but when trying to navigate still getting the same error.
EDIT :
I got it. You forgot the constructor in your login screen, that's why your props are empty :
constructor(props) {
super(props);
}
PREVIOUS ANSWER :
Without the full code, i can't see what the exact problem is, but i will give you an exemple of use of react-navigation :
In your index.js (start point of your app) :
import { AppRegistry } from 'react-native';
import { StackNavigator } from 'react-navigation';
export const AppNavigator = StackNavigator(Config.navigation);
AppRegistry.registerComponent('appName', () => AppNavigator);
In the navigation config :
const Config = {
navigation: {
login: {
screen: Login
},
setupProfile: {
screen: SetupProfile,
}
}
}
The first object found in the navigation config is the start of your app.
Now you can use your navigation function in the "login" page with navigate :
this.props.navigation.navigate('setupProfile')
If the AppRegistry is filled everything should run fine.
I hope it help !

Cannot nest react navigation in component - React Native

I'm having trouble nesting a react-navigation StackNavigator within a component - as detailed here https://reactnavigation.org/docs/intro/nesting#Nesting-a-Navigator-in-a-Component
However, even after following the guide to a T, I'm getting the following error -
route 'Home' should declare a screen
Here is my "GoHome.js" component which, in reference to the guide on https://reactnavigation.org, is the "NavigatorWrappingScreen"
/* #flow */
import React, { Component } from 'react';
import {
View,
Text,
StyleSheet,
} from 'react-native';
import { Constants, Location, Permissions } from 'expo';
import MainNavigator from '../navigation/MainNavigator';
import AppInfo from '../components/AppInfo/AppInfo';
import { MainStyle } from '../stylesheets/MainStyle';
export default class GoHome extends Component {
constructor(props){
super(props);
}
static navigationOptions = {
header: null,
};
componentWillMount(){
this._getLocationAsync();
}
_getLocationAsync = async () => {
let { status } = await Permissions.askAsync(Permissions.LOCATION);
if (status !== 'granted') {
console.log('Error - location access denied');
}else{
let location = await Location.getCurrentPositionAsync({});
console.log(location);
}
}
render() {
return (
<Image style = {MainStyle.imageContainer} source = {require('../assets/bg/bg_main.jpg')}>
<AppInfo />
<MainNavigator navigation = {this.props.navigation} />
</Image>
);
}
}
const styles = StyleSheet.create({
});
GoHome.router = MainNavigator.router;
And here is my MainNavigator.js component, which is the "MainScreenNavigator" component in the guide.
/* #flow */
import React, { Component } from 'react';
import {
View,
Text,
StyleSheet,
Image
} from 'react-native';
import { StackNavigator } from 'react-navigation';
import Register from '../components/Register/Register';
import Password from '../components/Password/Password';
import AppInfo from '../components/AppInfo/AppInfo';
import { MainStyle } from '../stylesheets/MainStyle';
import GoHome from '../screens/GoHome';
const NavigatorMain = StackNavigator({
Home: {
screen: GoHome
},
Register: {
screen: Register
},
Password: {
screen: Password
}
});
// export default class MainNavigator extends Component {
// render() {
// return (
// <NavigatorMain />
// );
// }
// }
const styles = StyleSheet.create({
});
export default NavigatorMain;
Any help AT ALL would be greatly appreciated.
TIA

Categories