Home > Net >  React Native - Cannot fetch API
React Native - Cannot fetch API

Time:06-20

I am using expo React Native for developing my app, Redux for state management, ExpressJS for backend, MongoDB as database.

I am trying to fetch logged-in user data, JWT tokens are not saved in cookies. I don't know if cookies work with react native or not? I have tested the API with postman, API is working and also JWT Tokens are saved in cookies when I test it with postman or thunder-client VS Code extension. Here is the code:

Backend:

exports.getUserDetails = catchAsyncErrors(async (req, res, next) => {
  const user = await User.findById(req.user.id);

  if (!user) {
    return next(new ErrorHandler("User not found", 404));
  }

  res.status(200).json({
    success: true,
    user,
  });
});

Redux State:

export const LoadUser = () => async (dispatch) => {
  try {
    dispatch({ type: "LOAD_USER_REQUEST" });
    const { data } = await axios.get(`${API_URL}/api/auth/me`);
    dispatch({
      type: "LOAD_USER_SUCCESS",
      payload: data.user, //Not loading data.
    });
  } catch (error) {
    dispatch({
      type: "LOAD_USER_FAIL",
      payload: error.response.data.message,
    });
  }
};

Frontend App.js file:

import { Provider as RNP_Provider } from "react-native-paper";
import { Provider } from "react-redux";
import Index from "./Index";
import { LoadUser } from "./actions/authAction";
import store from './store'
import { useEffect } from "react";

export default function App() {

  useEffect(() => {
    store.dispatch(LoadUser());
  }, [])

  return (
    <Provider store={store}>
      <RNP_Provider>
        <Index />
      </RNP_Provider>
    </Provider>
  );
}

CodePudding user response:

There is no such thing as cookies in mobile apps created in ReactNative. What you may use are AsyncStorages for Android/iOS and EncryptedStorage, search for those in npm and read the documentation, I guarantee you'll find your answers there!

You can also use some kind of context if you want your tokens to be saved for one session only, stores are suggested to use for values that you want to save for a longer time.

EncryptedStorage saves values even after app unninstall, so be careful with that one :)

  • Related