简体   繁体   中英

Interacting with localhost MongoDB and Sign up in React Native App

While trying to Sign Up using a form in the SignupScreen of the React-Native app, I am having issues with the the app not responding to my user signup API call. I tried to do a console.log and it ended up till my dispatch action but was not able to do a log inside the user api router. Below are the codes for the dispatch action and also the route handler.

// ACTIONS
  import axios from 'axios'
  // import AsyncStorage from '@react-native-community/async-storage';
  import AsyncStorage from '@react-native-async-storage/async-storage';

  import {USER_SIGNIN_REQUEST, USER_SIGNIN_SUCCESS, USER_SIGNIN_FAIL, USER_SIGNOUT,
      USER_SIGNUP_SUCCESS, REMOVE_ERROR, USER_SIGNUP_REQUEST, USER_SIGNUP_FAIL, 
      } from '../../constants/userConstants'

export const signUp = (name,email, password) => async (dispatch, getState) => {

    dispatch({ type: USER_SIGNUP_REQUEST, payload: { name, email, password } });

try {
  console.log('inside the seed') //Getting logs till this point only
    const { data } = await axios.post('/api/users/signup', { name, email, password});
    console.log(data) //not getting any logs from this
    dispatch({ type: USER_SIGNUP_SUCCESS, payload: data });
    dispatch({ type: USER_SIGNIN_SUCCESS, payload: data });
    dispatch({ type: REMOVE_ERROR, payload: null });
    console.log('inside the seed2')
    await AsyncStorage.setItem('userInfo', JSON.stringify(data));
}
catch (error) {
    dispatch({type: USER_SIGNUP_FAIL, payload: error.message  //app locally defined error
    });       
}

}

    //BACKEND ROUTE HANDLER
      userRouter.post(
        '/signup',
      expressAsyncHandler(async (req, res) => {
        console.log('inside the signup') //Not Getting Logs here
        const user = await User.findOne({ email: req.body.email });
        if (user) {
          res.status(401).send({ message: 'Email already exists' });
        }
        else {
          const user = new User({
            name: req.body.name,
            email: req.body.email,
            password: bcrypt.hashSync(req.body.password,4 ),
          });
          const createdUser = await user.save();
          res.send({
            _id: createdUser._id,
            name: createdUser.name,
            email: createdUser.email,
            token: generateToken(createdUser),
          });            
        }
        })         

);

I'm trying to be able to start up my App as either going unto Homescreen if logged in or to Sign Up screen if not using Redux Initial state and also Async Storage.

I have below code but everytime I try to access the userInfo in main App it always signs in my App and goes directly to homescreen even if no log in sessions has been done yet.

Surprisingly, I tried to log the initial userInfo which should be null if accessed from the AsyncStorage from the initial state but it shows below. It seems AsyncStorage creates this Object hence the App thinks that userInfo is not null. {"_1": 0, "_2": 1, "_3": undefined, "_4": null}

//  INITIAL STORE STATE 

// GETTING THIS IN IF I LOG USERINFO FROM REDUX STORE WHICH SHOULD BE NULL SINCE I HAVENT DONE ANY LOG IN YET. Async storage seems to put this object thats why my app thinks userInfo have contents.

      import AsyncStorage from '@react-native-async-storage/async-storage';
      import thunk from 'redux-thunk'
      import { composeWithDevTools } from '@redux-devtools/extension';
      import { userSignUpReducer, userSignInReducer }from './reducers/userReducers';

      const getData = async (key) => {
      let value;
      try {
          if(key=== 'userInfo'){
          value = await AsyncStorage.getItem(key) ? JSON.parse(AsyncStorage.getItem(key)) : null
          console.log(value)
          return
          }
          value = await AsyncStorage.getItem(key) ? JSON.parse(AsyncStorage.getItem(key)) : []
      } catch (error) {
      console.log(error); 
      }
        return value
      };

      const reducer = combineReducers({
        userSignIn: userSignInReducer,
        userSignUp: userSignUpReducer,
      })

      const initialState = {
        userSignIn: { userInfo: getData('userInfo')}
      };

      const configureStore = () => {
          return createStore(reducer,initialState,composeWithDevTools(applyMiddleware(thunk)));
      }


      export default configureStore; 


   // SIGNUP SCREEN 
  const handleSignUp = () => {
  dispatch(signUp( data.name, data.email, data.password));

   };


         //IN MAIN APP
        import { StatusBar } from 'expo-status-bar';
        import AsyncStorage from '@react-native-async-storage/async-storage';
        import React, { useState, useEffect } from 'react'
        import { useDispatch, useSelector } from 'react-redux';

        export default function App() {

          const userSignIn = useSelector(state => state.userSignIn);
          const { userInfo, loading, error } = userSignIn;
          const dispatch = useDispatch();

   useEffect(() => {

    console.log("ASYNC STORAGE CONTENTS")
    console.log(AsyncStorage)
    console.log("USER INFO CONTENTS")
    console.log(userInfo)
    return(() => {
    }
    )


      <SafeAreaProvider>
        <NavigationContainer>
        { userInfo ? (         
          // <Drawer/>
          <RootStack/>
          )
          :
          <RootStack/>
        }          
        </NavigationContainer>
      </SafeAreaProvider>



//INDEX.JS


import 'react-native-gesture-handler';
import { AppRegistry } from 'react-native';

import React from 'react';
import App from './App';
import { name as appName } from './app.json';
import { Provider } from 'react-redux';

import configureStore from './store/store';

const store = configureStore()

const RNRedux = () => (
  <Provider store = { store }>
    <App />
  </Provider>
)

AppRegistry.registerComponent('main', () => RNRedux);

   I have also just implemented the local database using mongo DB and inserted proxy field in the `package.json` file as `"proxy": "http://127.0.0.1:5000".` I also tried setting up android proxy in the settings of the android emulator. Server is running and connected to port 
  

      httpServer.listen(port, () => {
         console.log(`Serve at http://localhost:5000`);
        });

Appreciate any help on this problem. Thanks a lot.

Please share full code so that others can check your code. Your code is not enough to check. Maybe you made a mistake with import.

For example:

import axios from "axios"; ------------Right!
import {axios} from "axios" : -------------Wrong!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM