Redux Authentication Flow

 App.js

import React, { useState, useEffect } from 'react';
import { } from 'react-native';
import { Provider } from 'react-redux';
import { PersistGate } from 'redux-persist/lib/integration/react';
import { persistor, store } from './redux/Store';
// import Screen1 from './Components/Screen1';
// import AsyncStorage from '@react-native-async-storage/async-storage';
// import Screen2 from './Components/screen2'
// import Index1 from './Components/Screen2';
// import Screen5 from './Components/Screen5';
import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
// import {createSharedElementStackNavigator} from 'react-navigation-shared-element';
// import {createSharedElementStackNavigator} from
import 'react-native-gesture-handler';
import {
  increment,
  decrement,
  incrementvalue,
  decrementvalue,
  sendData,
} from './redux/actions/AuthActions';
import { connect } from 'react-redux';
import Index from './Components/Index';
import { useSelector } from 'react-redux';
// const Index = () => {
//   const Stack = createStackNavigator();
//   // const data = useSelector(state => state.auth.myarray);
const App = () => {
  // const Stack = createStackNavigator();
//   useEffect(() => {
//     console.log(state);
//   }, []);
// const state = useSelector(state => state.auth.myarray)
  return (

    <Provider store={store}>
      <PersistGate persistor={persistor} loading={null}>
        <Index />
      </PersistGate>
    </Provider>
  );
};
// function mapStateToProps(state) {
//   return {
//     // Mydata: state.auth.count,
//     Myarra: state.auth.myarray,
//   };
// }
export default App;
// export default connect(mapStateToProps, null)(App);

// import React,{useEffect} from 'react';
// import {View, Text,FlatList} from 'react-native';
// import styles from './styles';
// import { connect } from 'react-redux';
// const Screen5 = (props) => {
//     useEffect(() => {
//         console.log(props.Myarra);
//     }, [props.Myarra]);
//   return (
//     <View style={styles.container}>
//       <FlatList
//         data={props.Myarra}
//         keyExtractor={(item, index) => index.toString()}
//         renderItem={({item}) => (
//           <Text>
//             {item.WEIGHT},{item.AGE}
//           </Text>
//         )}
//       />
//     </View>
//   );
// };
// function mapStateToProps(state) {
//   return {
//     // Mydata: state.auth.count,
//     Myarra: state.auth.myarray,
//   };
// }
// function mapDispatchToProps(dispatch) {
//   return {
//     // PlusMyvalue: ()=> dispatch(incrementvalue()),
//     // mizasMyvalue: ()=> dispatch(decrementvalue()),
//     school: payload => dispatch(sendData(payload)),
//   };
// }

// export default connect(mapStateToProps, mapDispatchToProps)(Screen5);
//***********************************************************
Components index
index.js
import React, { useState, useEffect } from 'react';
import { } from 'react-native';

import Screen1 from '../Screen1';
import Screen5 from '../Screen5';

import { NavigationContainer } from '@react-navigation/native';
import { createStackNavigator } from '@react-navigation/stack';
// import {createSharedElementStackNavigator} from 'react-navigation-shared-element';
import 'react-native-gesture-handler';

import { connect } from 'react-redux';

const Index = props => {
    const Stack = createStackNavigator();
    useEffect(() => {
        console.log('helow ',props.Myarra.length);
    }, []);

    return (
        <NavigationContainer>
            <Stack.Navigator>
                {props.Myarra.length == 0 ? (
                    <Stack.Screen name="Screen1" component={Screen1} />
                ) : (
                    <Stack.Screen name="Screen5" component={Screen5} />
                )}
            </Stack.Navigator>
        </NavigationContainer>
    );
};
function mapStateToProps(state) {
    return {
        Myarra: state.auth.myarray,
    };
}

export default connect(mapStateToProps, null)(Index);

****************************************************************************
Screen1
index.js
import React, {useEffect, useState} from 'react';
import {View, Text, Button, TextInput, FlatList} from 'react-native';
import style from './styles';
// import { useNavigation } from '@react-navigation/native';

import {
  increment,
  decrement,
  incrementvalue,
  decrementvalue,
  sendData,
} from '../../redux/actions/AuthActions';
import {connect} from 'react-redux';
// import Screen2 from '../Screen2';
const Screen1 = props => {
  useEffect(() => {
    // console.log(props.Myarra);
    // retrieveData();
    setmyarraa(props.Myarra);
    // props.getdata(myarraa)
  }, [props.Myarra]);
  const [weight, setweight] = useState('');
  const [age, setage] = useState(0);
  const [myarraa, setmyarraa] = useState();

  // const gotoscreen2=()=>{

  // }
  // const retrieveData = async () => {
  //     try {
  //         if (props.Myarra !== null) {
  //             props.navigation.navigate('Screen5');
  //         }
  //     } catch (error) {
  //         // Error retrieving data
  //     }
  // };

  return (
    <View style={style.container}>
      {/* <Button onPress={() => props.PlusMyvalue()} title="+" /> */}
      <TextInput
        placeholder="enter name"
        style={style.inputweight}
        onChangeText={val => setweight(val)}
      />
      <TextInput
        placeholder="enter password"
        style={style.inputage}
        onChangeText={val => setage(val)}
      />
      <Button
        onPress={() => {
          if (weight == '' || age == 0) {
            alert('plase enter the value');
          } else {
            let schooldata = {
              WEIGHT: weight,
              AGE: age,
            };
            props.school(schooldata);
          }
        }}
        title="Login"
      />
      <Text style={style.txt}>{props.Mydata}</Text>
 <Button onPress={()=>props.mizasMyvalue()} title="-"/>
            {/* <Button
                title="dataScreen"
                onPress={() => props.navigation.navigate('Screen5')}
            /> */}
    </View>
  );
};

function mapStateToProps(state) {
  return {
    Mydata: state.auth.count,
    Myarra: state.auth.myarray,
  };
}
function mapDispatchToProps(dispatch) {
  return {
    // PlusMyvalue: ()=> dispatch(incrementvalue()),
    mizasMyvalue: ()=> dispatch(decrementvalue()),
    school: payload => dispatch(sendData(payload)),
  };
}
export default connect(mapStateToProps, mapDispatchToProps)(Screen1);
Screen1
styles.js
import { StyleSheet } from "react-native";

const style = StyleSheet.create({
    container:{
        flex:1,
        backgroundColor:'skyblue'
    },
    txt:{
        alignSelf:'center',
        fontSize:50
    },
    input:{
        // backgroundColor:'green',
        borderWidth:5,
        textAlign:'center'
    }
})

export default style;
******************************************************************************
Screen5
index.js
import React, { useEffect } from 'react';
import { View, Text, FlatList,Button } from 'react-native';
import styles from './styles';
import { connect } from 'react-redux';
import { logout } from '../../redux/actions/AuthActions';
const Screen5 = props => {
  useEffect(() => {
    console.log(props.Myarra);
  }, [props.Myarra]);

  return (
    <View style={styles.container}>
      <FlatList
        data={props.Myarra}
        keyExtractor={(item, index) => index.toString()}
        renderItem={({ item }) => (
          <Text>
           username: {item.WEIGHT},password{item.AGE}
          </Text>
        )}
      />
      <Button onPress={()=>props.logouting()} title="logout" />
    </View>
  );
};
function mapStateToProps(state) {
  return {
    // Mydata: state.auth.count,
    Myarra: state.auth.myarray,
    // logouting:state.auth.myarray
  };
}
function mapDispatchToProps(dispatch) {
  return {
    // PlusMyvalue: ()=> dispatch(incrementvalue()),
    logouting: ()=> dispatch(logout()),
    school: payload => dispatch(sendData(payload))
  };
}

export default connect(mapStateToProps, mapDispatchToProps)(Screen5);
Screen5
styles.js
import { StyleSheet } from "react-native";

const styles = StyleSheet.create({
    container:{
        flex:1,
        backgroundColor:'yellow'
    }
})

export default styles
***************************************************************************

Redux


actions AuthActions.js
import { INCREMENT, DECREMENT, SCHOOL, LOGOUT } from '../types';

// export const LanguageType = (language) => ({
//     type: LANGUAGE,
//     payload: language,
// });

// export const increment = (num) => ({
//     type: INCREMENT,
//     payload: num,
// });
// export const decrement = (num) => ({
//     type: DECREMENT,
//     payload: num,
// });

console.log('hellow sherkhan ');
export const logout = () => ({
    type: LOGOUT,
});
export const incrementvalue = () => ({
    type: INCREMENT,
});
export const decrementvalue = () => ({
    type: DECREMENT,
});

export const sendData = data => ({
    type: SCHOOL,
    payload: data,
});

reducers authReducers.js
import { INCREMENT, DECREMENT, SCHOOL, LOGOUT } from '../types';

const initialState = {
    count: 0,
    myarray: [],
};

export default function (state = initialState, action) {
    switch (action.type) {
        case INCREMENT:
            console.log(' i am called');
            return {
                ...state,
                count: state.count + 1,
            };

        case DECREMENT:
            console.log(' i am Decrement');
            return {
                ...state,
                count: state.count - 1,
            };

        case SCHOOL: // [{asasa},{sasa}]
            let DummyArray = [...state.myarray, action.payload];

            return {
                ...state,
                myarray: DummyArray,
            };
        case LOGOUT:
            console.log(' logout calling');
            return {
                ...state,
                myarray:state.myarray = []
            };
        default:
            return state;
    }
}

redux
rootReducer.js
import { combineReducers } from 'redux';
import authReducers from './reducers/authReducers';

const rootReducer = combineReducers({
    auth: authReducers,
});
export default rootReducer;

redux
Store.js
// import AsyncStorage from '@react-native-community/async-storage';
import AsyncStorage from '@react-native-async-storage/async-storage';
import { createStore, applyMiddleware } from 'redux';
import thunk from 'redux-thunk';
import { persistStore, persistReducer } from 'redux-persist';
import rootReducer from './rootReducer';

const persistConfig = {
    key: 'root',
    storage: AsyncStorage,
    whitelist: ['auth'],
    blacklist: [''],
};

const persistedReducer = persistReducer(persistConfig, rootReducer);
const store = createStore(persistedReducer, applyMiddleware(thunk));
let persistor = persistStore(store);
export { store, persistor };


redux
types.js

export const LANGUAGE = 'LANGUAGE'
export const INCREMENT = 'INCREMENT'
export const DECREMENT = 'DECREMENT'
export const SCHOOL = 'SCHOOL'
export const LOGOUT = 'LOGOUT'




***************************************************************************
***************************************************************************
pkg.json
  "dependencies": {
    "react": "17.0.2",
    "react-native": "0.66.3",
    "@react-native-async-storage/async-storage": "^1.15.9",
    "@react-native-masked-view/masked-view": "^0.2.6",
    "@react-navigation/native": "^6.0.6",
    "@react-navigation/stack": "^6.0.11",
    "react-native-gesture-handler": "^1.10.3",
    "react-native-safe-area-context": "^3.3.2",
    "react-native-screens": "^3.9.0",
    "react-redux": "^7.2.5",
    "redux": "^4.1.1",
    "redux-persist": "^6.0.0",
    "redux-thunk": "^2.3.0"

Comments

Popular posts from this blog

NFC Checker App Privacy Policy

Privacy Policy For Real Love Calculator-Prank app

Privacy Policy for Live Weather Forecast - Realtime app