現在、APIの結果によって表示するコンポーネントを切り替える処理を実装しています。
useEffectを使って画面をロードするタイミングで、
APIを呼び出しJsonオブジェクトとして結果を受け取っていますが、
該当データがない場合はオブジェクトが空で返ってきます。
その結果に応じて、return内で三項演算子を使って表示を切り替えたいと思っておりますが、該当データがある場合も『無い』と表示されてしまいます。
コードは下記の内容になります。
アドバイス頂けると助かります。よろしくお願い致します!
関連するコード
package.json
"expo": "~44.0.0",
"expo-cli": "^5.0.3",
"axios": "^0.24.0",
"react": "17.0.1",
"react-native": "0.64.3",
Home.jsx
import React, { useContext, useEffect, useState } from 'react';
import {
View, ScrollView, Text, StyleSheet, Image,
} from 'react-native';
import axios from 'axios';
import { AuthContext } from '../features/auth/AuthContext';
export default function Home(props) {
const { navigation } = props;
const { token } = useContext(AuthContext);
console.log(token);
const [profile, setProfile] = useState('');
const [hasProfile, setHasProfile] = useState(false);
useEffect(() => {
axios
.get(`${api}api_app/myprofile/`, {
headers: {
'Content-Type': 'application/json',
Authorization: `JWT ${token}`,
},
})
.then((res) => {
console.log(res.data);
setProfile(res.data[0]);
})
.catch((res) => {
console.log(res);
setHasprofile();
});
}, []);
return (
<View>
<View>
{hasProfile ?
(
<Text>{profile.name}</Text>
) :
(
<Text>プロフィールがない</Text>
)
}
</View>
</View>
);
}