Does anyone knows how can i fix this error? the error clearly says that LOG [TypeError: null is not an object (evaluating 'JSON.parse(value).token')] but i dont know what went wrong , Can anyone check my code and tell me what i did wrong? i checked my code spellings but i can't find my problem my backend is also running
import { StyleSheet, View, StatusBar, Text, Image, ActivityIndicator } from 'react-native';
import React, { useEffect, useState } from 'react';
import ButtomNavbar from '../../Components/ButtomNavbar';
import TopNavbar from '../../Components/TopNavbar';
import { formHead } from '../../CommonCss/FormCss';
import { ScrollView } from 'react-native-gesture-handler';
import defaultprofileimg from '../../../assets/profileimg.jpg';
import AsyncStorage from '@react-native-async-storage/async-storage';
const Profile = ({ navigation }) => {
const [userdata, setUserdata] = useState(null)
useEffect(() => {
AsyncStorage.getItem('user')
.then(async (value) => {
fetch('http://10.0.2.2:3000/userdata', {
method: 'POST',
headers: {
'Content-Type': 'application/json',
'Authorization' : 'Bearer' JSON.parse(value).token
},
body: JSON.stringify({ email: JSON.parse(value).user.email })
})
.then(res => res.json()).then(data => {
if (data.message == 'User Data Fetched Susscessfully') {
setUserdata(data.user)
}
else {
alert('Something went wrong')
navigation.navigate('login')
}
})
.catch(err => {
alert(err)
console.log(err)
})
})
.catch(err => {
alert(err)
console.log(err)
})
}, [])
console.log(userdata)
return (
<View style={styles.container}>
<StatusBar />
<ButtomNavbar navigation={navigation} page={'profile'} />
<TopNavbar navigation={navigation} page={'profile'} />
{
userdata? <ScrollView>
<View style={styles.section1}>
{
userdata.profileImg.length>0 ?
<Image style={styles.profileimg} source={{ uri: userdata.profileImg}} />
:
<Image style={styles.profileimg} source={defaultprofileimg} />
}
<Text style={styles.usernameText}>@{userdata.username}</Text>
<View style={styles.Postrow}>
<View style={styles.Postrow1}>
<Text style={styles.followerTxt}>UpVotes</Text>
<Text style={styles.UpVote}>{userdata.upvotes.length}</Text>
</View>
<View style={styles.verticalLine}></View>
<View style={styles.Postrow1}>
<Text style={styles.followerTxt}>DownVotes</Text>
<Text style={styles.UpVote}>{userdata.donwvotes.length}</Text>
</View>
<View style={styles.verticalLine}></View>
<View style={styles.Postrow1}>
<Text style={styles.followerTxt}>Posts</Text>
<Text style={styles.UpVote}>{userdata.posts.length}</Text>
</View>
</View>
{/* <Text style={styles.decs}>Hello this is des</Text> */}
</View>
{
userdata.posts.length > 0 ? <View style={styles.section1}>
<Text style={styles.postTxt}>Your Posts</Text>
<View style={styles.posts}>
{
userdata.posts.map((item) => {
return (
<Image key={item.id} style={styles.Postimage} source={{ uri: item.posts }} />
)
})
}
</View>
</View>
:
<View style={styles.noPost}>
<Text style={styles.noposttxt}>User not posted anything yet</Text>
</View>
}
</ScrollView>
:
<ActivityIndicator color='white' size='large' />
}
</View>
)
}
export default Profile
my backend code:
router.post('/userdata', (req, res) => {
const { authorization } = req.headers;
if (!authorization) {
return res.status(401).json({ error: 'You must be logged in, token not given' });
}
const token = authorization.replace("Bearer", "");
console.log(token);
jwt.verify(token, process.env.JWT_SECERT, (err, payload) => {
if (err) {
return res.status(401).json({ error: 'You must be logged in, token invalid' })
}
const { _id } = payload;
User.findById(_id).then(
userdata => {
res.status(200).send({ message: 'User Found', user: userdata })
})
})
})
From here i get the user:
const handleLogin = () => {
if (email == '' || password == '') {
alert('Please enter email and password')
}
else {
setLoading(true)
fetch('http://10.0.2.2:3000/login', { // for emultor 'http://10.0.2.2:3000/signup
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
email,
password
})
})
.then(res => res.json())
.then(async data => {
if (data.error) {
setLoading(false)
alert(data.error)
}
else if (data.message == 'Successfully Signed In') {
setLoading(false)
await AsyncStorage.setItem('user', JSON.stringify(data))
navigation.navigate('home', { data })
}
})
.catch(err => {
setLoading(false)
alert(err)
})
}
}
Login code:
router.post('/login', (req, res) => {
const { email, password } = req.body;
if (!email || !password) {
return res.status(422).json({ error: 'Please fill all the fields' })
}
else {
User.findOne({ email: email })
.then(savedUser => {
if (!savedUser) {
return res.status(422).json({ error: 'invaile cnreditnions' })
}
else {
bcrypt.compare(password, savedUser.password)
.then(
doMatch => {
if (doMatch) {
const token = jwt.sign({ _id: savedUser._id }, process.env.JWT_SECERT);
const { _id, username, email } = savedUser;
res.json({ message: 'Successfully Signed In', token, user: { _id, username, email } });
}
else {
return res.status(422).json({ error: 'invaile cnreditnions' })
}
}
)
}
})
.catch(err => {
console.log(err)
})
}
})
CodePudding user response:
i fixed that issue the problem was with login when i logout than login again than the issue solved, i am currenlty in my development phase So in my App.js i am dirctly navigating to home page without loging but accoding to the code logic after Successfully login i will get token So now i fixed it
CodePudding user response:
Well the error simply indicates that the value that you are trying to parse is not an object rather it is a null value. Try to do optional chaining while re-renders and also check your api response of token
. The value coming as response is clearly not an object. Try to debug using console.log(value)
and add some error boundaries like loading and error states and accordingly manage the UI. You will be good to go.