xv8
xv8

Reputation: 176

How to get signed in users data?

I have a MERN mobile app thats using passportjs to authenticate and login users (with mongodb database and axios), however, when i eventually get to the the screen to enter in data (a "log"), i cant associate that data/log with the signed in user. How can i grab the user id several screens later after they have already signed in to associate it with the entry? My mongodb database has a number of users, so i only want a specific user's data (eg calories), ie the one that is currently logged in:

// Mongoose schemas
// log.model.js
const Schema = mongoose.Schema;
const logSchema = new Schema(
    {
        user: {
            type: mongoose.Schema.Types.ObjectId,
            ref: "User",
        },
        calories: {
            type: Number,
            required: true,
        },
    },
    {
        timestamps: true,
    }
);
const Log = mongoose.model("Log", logSchema);

// user.model.js
const userSchema = new Schema(
    {
        _id: Schema.Types.ObjectId, // user id
        email: {
            type: String,
            required: true,
            unique: true,
            trim: true,
        },
        password: {
            type: String,
            required: true,
            trim: true,
            minlength: 6,
        },
    },
    {
        timestamps: true,
    }
);
const User = mongoose.model("User", userSchema);

They are first prompted to signin in the app, where they will then navigate to Home. Not all features are added in yet, just in development stage now:

// ./frontend/screens/signin.js
function onLoginPress() {
        axios({
            method: "POST",
            data: {
                email: email,
                password: password,
            },
            withCredentials: true,
            url: 'http:localhost:5000/users/signin',
        })
            .then((res) => console.log(res.data))
            .catch((error) =>
                console.log("ERROR: Promise rejected (sign in): " + error)
            );
        navigation.navigate("Home");
}

// ./backend/routes/users.js
router.route("/signin").post((req, res, next) => {
    passport.authenticate("local", (error, user, info) => {
        if (error) {
            res.json({
                status: "FAILED",
                message: error,
            });
        }
        if (!user) {
            res.json({
                status: "FAILED",
                message: "No user exists",
            });
        } else {
            req.logIn(user, (error) => {
                if (error) console.log("ERROR: " + error);
                res.json({
                    status: "SUCCESS",
                    message: "Successfully authenticated",
                });
                console.log(req.user);
            });
        }
    })(req, res, next);
});

After they sign in, and they wish to enter in calories, i attempt to associate that log (and any future logs they might add) with the signed in user when they hit a button:

// ./frontend/screens/log.js
const [calories, setCalories] = React.useState("");

function onSaveLog() {
       axios({
            method: "post",
            url: "http://localhost:5000/log/add",
            data: {
                calories: calories,
                // CANT GET USER ID HERE?
            },
        })
            .then((res) => {
                console.log(res.data);
            })
            .catch(function () {
                console.log("LOG ERROR: promise rejected");
            });
}

// ./backend/routes/log.js
router.route("/add").post((req, res) => {
    const calories = Number(req.body.calories);
    // const user = req.body.user; // CANT GET THE USER ID HERE

    const newLog = new Log({
        calories,
        // user,
    });

    // saves Log data to mongodb
    newLog
        .save()
        .then(() => res.json("Log added"))
        .catch((err) => res.status(400).json("Error: " + err));
});

Upvotes: 0

Views: 1113

Answers (1)

Gaurav Roy
Gaurav Roy

Reputation: 12225

so, what you doubt is, correct me if I'm wrong is that you want an ID that can be accessed somewhere later in the app to retrieve the users' data.

There are many ways to achieve that,

  1. after you get the id, you can pass it as Navparams. check this for more info RN- params
  2. Next you can store the id in async storage and retrieve it anywhere, I would suggest this cause is the easiest rn--async storage

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

const storeData = async (value) => {
  try {
    await AsyncStorage.setItem('@storage_Key', value)
  } catch (e) {
    // saving error
  }
}

// read
const getData = async () => {
  try {
    const value = await AsyncStorage.getItem('@storage_Key')
    if(value !== null) {
      // value previously stored
    }
  } catch(e) {
    // error reading value
  }
}

you can do it this way, do tell me if you're stuck

Upvotes: 1

Related Questions