Im simply trying to copy the Nested objects i get back from the axios GET request to my react-native hook. Not straightforward it seems. Data would look something like this for example:
[
{
_id: 61242b08013a5f26bd1b2d47,
user: '6110675d65e1528d03a8bce6',
totalCalories: 7,
totalProtein: 7,
createdAt: 2021-08-23T23:11:04.076Z,
updatedAt: 2021-08-24T00:53:38.621Z,
__v: 0
},
{
_id: 6125990e9669cc6b466c37b5,
user: '6110675d65e1528d03a8bce6',
__v: 0,
createdAt: 2021-08-25T01:12:44.343Z,
totalCalories: 2,
totalProtein: 2,
updatedAt: 2021-08-25T01:14:01.439Z
}
]
However, i get a component exception: undefined is not an object
error, as well as a 404 error when trying to access it via historyData
in my frontend. Here is my component which renders the history screen in my iOS app:
Frontend:
const History = () => {
const [currentUsersID, setCurrentUsersID] = React.useState("");
const [historyData, setHistoryData] = React.useState();
// Gets the current user's ID from local storage
const getData = async () => {
try {
const value = await AsyncStorage.getItem("@storage_Key");
if (value !== null) {
setCurrentUsersID(value);
}
} catch (error) {
console.log("Error reading AsyncStorage value -> " + error);
}
};
getData();
async function getHistory() {
try {
const response = await axios.get("http://localhost:5000/daysLog/getLog/" + currentUsersID);
setHistoryData(() => {
return response.data;
});
} catch (error) {
console.log("ERROR (getHistory) -> " + error);
}
}
useFocusEffect(
React.useCallback(() => {
getHistory();
})
);
return (
<SafeAreaView style={styles.container}>
<StatusBar barStyle="light-content" />
<Text style={{ color: "white" }}>
History: {historyData[0].totalCalories} // ERROR HERE
</Text>
</SafeAreaView>
);
};
Backend:
const router = require("express").Router();
let daysLog = require("../models/daysLog.model");
// getting the user's existing daysLogs
router.route("/getLog/:userID").get((req, res) => {
daysLog
.find({
user: req.params.userID,
})
.then((logs) => res.json(logs))
.catch((error) =>
res.status(400).json("Error (dayLog/GET) -> " + error)
);
});
historyData[0].totalCalories is throwing that because it will take time for it to get fetched while you're waiting for a response. You should have a block to test if historyData is not nul before you render the result.
Also get history focus effect relies on currentUser being valid but there's no expression that ensures it the way you wrote it. At best it's a race condition. Consider changing your focus effect to be a regulaf effect and make the currentUserId it's dependency.
Then inside of it to you can check if currentUserId is not null and start fetching get history accordingly.