I'm learning Redux. I don't konw why syntax error appear.
I'm building a simple counter app.
This is my code. I don't well react-native and redux. so I really need help.Plase help me.
I don't know where I'm wrong. I think problem is View.js.
App.js
`import React from 'react';
import Screen from './src/View';
import { Provider,createStore } from 'react-redux';
const store = createStore(reducers);
const App=()=>{
return(
<Provider store={store}>
<Screen/>
</Provider>
)
}
export default App;`
View.Js
This part have syntax error.
import React from "react";
import { StyleSheet,View, Text, Button } from "react-native";
import { connect } from 'react-redux';
export default function Screen (){
return(
<View >
<Text style={styles.containers}>counter: </Text>
<Text style={styles.containers}>{this.props.state.counterNum}</Text>
<Button title="+" >+</Button>
<Button title="-" >-</Button>
</View>
);
};
const styles=StyleSheet.create({
containers : {
textAlign:"center",
}
}
);
function mapStateToProps(state){
return {
state: state.counterNum
};
}
// Actions을 props로 변환
function matchDispatchToProps(dispatch){
return bindActionCreators({
counter : counterNum
}, dispatch);
}
//(error here)
export default connect(mapStateToProps, matchDispatchToProps)(Screen)
index.js
export const INCREMENT = 'INCREMENT';
export const DECREMENT = 'DECREMENT';
const initialState={
counter:[
{
counterNum:0,
},
],
};
const counter=( state= initialState, action)=>{
const {counter}=state;
switch(action.type){
case 'INCREMENT':
return({
counter:[
...counter.slice(0,action.index),
{
counterNun : counter[action.index].counterNum +1,
}
]
});
case 'DECREMENT' :
return({
counter:[
...counter.slice(0,action.index),
{
counterNun : counter[action.index].counterNum -1,
}
]
});
default :
return state;
}
}
export default counter;
Any help/knowledge will be appreciated thanks!
It looks like you are trying to use syntax for class components.
Try passing props into Screen like this:
export default function Screen (props){
return(
<View >
<Text style={styles.containers}>counter: </Text>
<Text style={styles.containers}>{props.state}</Text>
<Button title="+" >+</Button>
<Button title="-" >-</Button>
</View>
);
};
no need for this keyword
Also, would be better to do this:
function mapStateToProps(state){
return {
counterNum: state.counterNum // <-- change property name to counterNum
};
}
then you can access this value with props.counterNum
Related
Hey struggling with this one for a day now.
I am trying to store game data just the gameId and the Level for example Game 1 Level 12
Here is my screen
import React, { Component } from 'react';
import AsyncStorage from '#react-native-async-storage/async-storage';
import { Text, StyleSheet, Button, View, ImageBackground, Pressable } from 'react- native';
import bg from "../assets/images/1.jpg";
import styles from '../assets/style';
import { NavigationContainer } from '#react-navigation/native';
import { createStackNavigator } from '#react-navigation/stack';
const setScore = async (gameId, level) => {
//// SETS THE SCORE
try {
await AsyncStorage.setItem(scoreKey, level);
console.log(value)
} catch (error) {
console.log(error)
}
};
const getScore = async (gameId) => {
try {
let value = await AsyncStorage.getItem(JSON.stringify(gameId))
if(value !== null) {
// value previously stored
return JSON.stringify(value)
} else {
return "not started"
}
} catch(e) {
// error reading value
}
};
/// This would add game 1 and level 12
setScore('1','12') /// This part works
const theLevel = getScore(1)
export default function Home({navigation, route}) {
return (
<ImageBackground source={bg} resizeMode="cover" style={styles.imageBG}>
<View style={styles.GameList}>
<Text style={styles.mainTitle}>Current Level is {theLevel}</Text>
</View>
</ImageBackground>
);
}
At the bottom of the above code I want to display the level but I get the error
Error: Objects are not valid as a React child (found: object with keys {_U, _V, _W, _X}). If you meant to render a collection of children, use an array instead.
However If I alert(theLevel) it works fine can someone tell me what I am doing wrong please
Call getScore function from within useEffect hook of your Home component.
export default function Home({ navigation, route }) {
const [level, setLevel] = useState(0);
useEffect(() => {
async function getMyLevel() {
const lvl = await getScore(1);
setLevel(lvl);
}
getMyLevel();
}, []);
const onPress = async () => {
await setScore('1','12');
};
return (
<ImageBackground source={bg} resizeMode="cover" style={styles.imageBG}>
<View style={styles.GameList}>
<Text style={styles.mainTitle}>Current Level is {level}</Text>
</View>
<Button title="Set Score" onPress={onPress} />
</ImageBackground>
);
}
I am new to RN development.
I am trying to setup Apollo client to fetch GraphQL data.
I am not able to get the data back.
Here is the code in App.js
import {ApolloProvider} from '#apollo/client';
import AppNavigator from './app/navigation/AppNavigator';
import apiClient from './app/api/client';
function App(props) {
console.log('From Main Component');
return (
<ApolloProvider client={apiClient}>
<NavigationContainer>
<AppNavigator />
</NavigationContainer>
</ApolloProvider>
);
}
In AppNavigator, Im displaying only the home screen for now.
In ./app/api/client.js
import {ApolloClient, InMemoryCache} from '#apollo/client';
const apiClient = new ApolloClient({
uri: 'https://phccapi-dev.azure-api.net/NaraakomGraphQLGateway/graphql',
cache: new InMemoryCache(),
headers: {
authorization:'Bearer xxxxxxxxxxxxxx',
'Subscription-Key': 'xxxxxxxxxxxxxxxxxx',
},
});
export default apiClient;
In api/queries.js
import {gql} from '#apollo/client';
export default {
GET_USER_NAME,
};
//Used in the Home Screen
const GET_USER_NAME = gql`
query {
userProfile {
fName
lName
}
}
`;
In HomeScreen.js
import DisplayData from '../components/DisplayData';
function HomeScreen({navigation}) {
return (
<View>
<Text> Home Screen text </Text>
<DisplayData/>
<Button title="Profile" onPress={() => navigation.navigate('Profile')} />
</View>
);
}
export default HomeScreen;
In DisplayData.js
import {useQuery} from '#apollo/client';
import GET_USER_NAME from './../api/queries';
function DisplayData(props) {
console.log('Logging query : ' + GET_USER_NAME);
const {loading, error, data} = useQuery(GET_USER_NAME);
if (loading) {
console.log('Loading : ' + loading);
return (
<View>
<Text>Loading...</Text>
</View>
);
}
if (error) {
console.log('Error : ' + error);
return (
<View>
<Text>Error :</Text>
</View>
);
}
console.log('Data : ' + data);
return (
<View>
<Text> In Component </Text>
<Text> {data.userProfile.fName} </Text>
</View>
);
}
export default DisplayData;
From GraphiQL, if I run the query I am getting the data.
If I follow the Apollo Client Documentation https://www.apollographql.com/docs/react/get-started/ and put all code in a single file , I am able to get the data
But most tutorials that I have gone through suggest to follow a hierarchy , a folder structure to properly maintain code and separate the concerns as the app grows
Hence I have tried to separate different things in different files and components
But I think I have not been able to set it up properly.
Before learning RN , I have also just learned JS and React
So I am guessing that there could also be some issue in the way I have declared constants/components , exported and imported them
I'm doing a simple counter app. It has one label, and a button that you can increment by + 1 (each time it's pushed).
Using redux, I want to use the count that I store (in my Redux Store) in App.js file. However, I'm getting an error:
Error: could not find react-redux context value; please ensure the component is wrapped in a Provider
Using the useSelector works in other files, just not App.js. Is there a work around?
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import Dogs from './components/Dogs';
import { Provider, useSelector } from 'react-redux';
import store from './redux/configureStore'
export default function App() {
const count = useSelector((state) => state.counter.count);
{/*useSelector does not work in this file!*/}
return (
<Provider store={store}>
<View style={styles.container}>
<Text>{`ha ${count}`}</Text>
<Dogs />
</View>
</Provider>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
Counter.js
import React, { useState, useEffect } from "react";
import { View, Text, StyleSheet, Button} from "react-native";
import { useDispatch, useSelector } from "react-redux";
import { increment } from '../redux/ducks/counter'
const Counter = () => {
const count = useSelector((state) => state.counter.count);
{/*useSelector works in this file!*/}
const dispatch = useDispatch();
const handleIncrement = () => {
dispatch(increment())
};
return (
<div>
{/* <Text>{` COunt: ${count}`}</Text> */}
<Button onPress={handleIncrement}>Increment</Button>
</div>
);
}
const styles = StyleSheet.create({})
export default Counter;
redux/configureStore.js
import { combineReducers, createStore } from 'redux';
import counterReducer from './ducks/counter';
const reducer = combineReducers({
counter: counterReducer
});
const store = createStore(reducer);
export default store;
redux/ducks/counter.js
const INCREMENT = 'increment';
export const increment = () => ({
type: INCREMENT
})
const initialState = {
count: 0
};
export default ( state = initialState, action) => {
switch(action.type) {
case INCREMENT:
return{...state, count: state.count + 1}
default:
return state;
}
};
As error saying, you are using useSelector out side of provider. In your app.js you are using useSelector before the app renders, so it is not able to find store. So, create a component for functionality which you want to use in app.js like this :
Create a file, call it anything like CountView.js, in CountView.js use your redux login :
CountView.js
import React from 'react';
import { Text } from 'react-native';
import { useSelector } from 'react-redux';
const CountView = () => {
const count = useSelector((state) => state.counter.count);
return (
<Text>{`ha ${count}`}</Text>
)
}
export default CountView;
Now, In your app.js use this component :
import React from 'react';
import { StyleSheet, Text, View } from 'react-native';
import Dogs from './components/Dogs';
import { Provider } from 'react-redux';
import store from './redux/configureStore'
import CountView from '../components/CountView'; // import CountView component
export default function App() {
return (
<Provider store={store}>
<View style={styles.container}>
{/* Use component here */}
<CountView />
<Dogs />
</View>
</Provider>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
alignItems: 'center',
justifyContent: 'center',
},
});
Keep other things as it is, and now your functionality will works.
useSelector will work only if you wrap it inside Provider. you can create a wrapper file for App.
const AppWrapper = () => {
return (
<Provider store={store}> // Set context
<App /> // Now App has access to context
</Provider>
)
}
In App.js
const App = () => {
const count = useSelector((state) => state.counter.count); // will Work!
}
Unlike a regular React application, an expo React-Native application is not wrapped using an index.js file. Therefore when we wrap the provider in app.js for a React-Native app, we wrap it in index.js for React application. So the hooks like useSelector or useDispatch run before the provider is initialized. So, I would suggest not using any hooks in the app component, instead, we can create other components in the app.js and use the hooks in a separate component like in the code I have used below.
const Root = () => {
const [appIsReady, setAppIsReady] = useState(false);
const dispatch = useDispatch();
const fetchToken = async () => {
const token = await AsyncStorage.getItem("token");
console.log("Stored Token: ", token);
if (token) {
dispatch(setAuthLogin({ isAuthenticated: true, token }));
}
};
const LoadFonts = async () => {
await useFonts();
};
useEffect(() => {
async function prepare() {
try {
await SplashScreen.preventAutoHideAsync();
await LoadFonts();
await fetchToken();
} catch (e) {
console.warn(e);
} finally {
setAppIsReady(true);
}
}
prepare();
}, []);
const onLayoutRootView = useCallback(async () => {
if (appIsReady) {
await SplashScreen.hideAsync();
}
}, [appIsReady]);
if (!appIsReady) {
return null;
}
return (
<NavigationContainer onReady={onLayoutRootView}>
<MainNavigation />
</NavigationContainer>
);
};
export default function App() {
return (
<>
<Provider store={store}>
<ExpoStatusBar style="auto" />
<Root />
</Provider>
</>
);
}
I am creating a slide bar, In that, I have used the react-redux library. When I call the class which contains the redux-code, it works fine. I want to show this slide bar after login. Therefore, with conditions (I set a state variable if user login successfully then only this page should get rendered), I tried to call the same file which shows a blank page. I printed the console log. I am able to print all the logs. But with conditions, I am not able to load the data.
I don't know much about react-redux.Can you assist me to resolve this?
My code is,
main.js,
import React, {Component} from 'react';
import {
StyleSheet,
Dimensions,
Platform,
View,
StatusBar,
DrawerLayoutAndroid,
} from 'react-native';
import { createStore } from 'redux';
import { Provider } from 'react-redux';
import reducer from '../Redux/reducers';
import { setNavigator, setActiveRoute } from "../Redux/actions";
import DrawerContent from '../Navigation/DrawerContent';
import Toolbar from '../Navigation/Toolbar';
import AppNavigation from '../Navigation/AppNavigation';
import { bgStatusBar, bgDrawer } from '../global.styles';
let store = createStore(reducer);
/* getDrawerWidth Default drawer width is screen width - header width
* https://material.io/guidelines/patterns/navigation-drawer.html
*/
const getDrawerWidth = () => Dimensions.get('window').width - (Platform.OS === 'android' ? 56 : 64);
export default class Main extends Component {
constructor() {
super();
this.drawer = React.createRef();
this.navigator = React.createRef();
}
componentDidMount() {
store.dispatch(setNavigator(this.navigator.current));
}
openDrawer = () => {
this.drawer.current.openDrawer();
};
closeDrawer = () => {
this.drawer.current.closeDrawer();
};
getActiveRouteName = navigationState => {
if (!navigationState) {
return null;
}
const route = navigationState.routes[navigationState.index];
// dive into nested navigators
if (route.routes) {
return getActiveRouteName(route);
}
return route.routeName;
};
render() {
return (
<Provider store={store}>
<DrawerLayoutAndroid
drawerWidth={getDrawerWidth()}
drawerPosition={DrawerLayoutAndroid.positions.Left}
renderNavigationView={
() => <DrawerContent closeDrawer={this.closeDrawer} />
}
ref={this.drawer}
>
<View style={styles.container}>
<StatusBar
translucent
animated
/>
<Toolbar showMenu={this.openDrawer} />
<AppNavigation
onNavigationStateChange={(prevState, currentState) => {
const currentScreen = this.getActiveRouteName(currentState);
store.dispatch(setActiveRoute(currentScreen));
}}
ref={this.navigator}
/>
</View>
</DrawerLayoutAndroid>
</Provider>
);
}
}
Login.js
import Main from './main';
render() {
return (
<View>
{this.state.isLoggedIn ?
<Main/>
:
<ChangePassword isUpdatePassword={this.state.isUpdatePassword} callLogin={this.callLogin}/>
);
}
}
If I just call Main class inside render method it works. But It does not work with conditions.
in a handleClick function, update the rootSiblings like this,
handleClick() { this.progressBar.update( <ProgressBar /> ); }
and in ProgressBar component,
import React, { PropTypes } from 'react';
import { connect } from 'react-redux';
import { View } from 'react-native';
const getFinishedWidth = progress => ({ width: progress * totalWidth });
const getUnfinishedWidth = progress => ({ width: (1 - progress) * totalWidth });
function CustomerReassignProgressBar(props) {
const { progress } = props;
return (
<View style={styles.bar}>
<View style={getFinishedWidth(progress)} />
<View style={getUnfinishedWidth(progress)} />
</View> );
}
CustomerReassignProgressBar.propTypes = { progress: PropTypes.number, };
const mapStateToProps = state => ({ progress: state.batchReassignProgress, });
export default connect(mapStateToProps)(ProgressBar);
then, when calling handleClick(), the app crushed, the error is, 'Could not find "store" in either the context or props of "Connect(ProgressBar)". Either wrap the root component in a , or explicitly pass "store" as a prop to "Connect(ProgressBar)".'
if I don't use connect in component, it works well. So, I guess, maybe rootSiblings can not work with react-redux. But does anyone knows this problem?
Upgrade to react-native-root-siblings#4.x
Then
import { setSiblingWrapper } from 'react-native-root-siblings';
import { Provider } from 'react-redux';
const store = xxx;// get your redux store here
// call this before using any root-siblings related code
setSiblingWrapper(sibling => (
<Provider store={store}>{sibling}</Provider>
));