Vamos começar criando um arquivo dentro de services chamado de profileService.ts, e nele vamos criar a estrutura e o serviço de getInfo
import api from "./api";
import * as SecureStore from "expo-secure-store";
import AsyncStorage from "@react-native-async-storage/async-storage";
const profileService = {
getUserProfile: async () => {
const token = await SecureStore.getItemAsync("onebitshop-token");
const user = await AsyncStorage.getItem("user");
const { _id } = JSON.parse(user || "");
const res = await api.get(`/users/${_id}`, {
headers: {
Authorization: `Bearer ${token}`,
},
});
return res;
},
};
export default profileService;
Com isso feito, nós podemos receber as informações na tela de usuário e então vamos para userProfile e começaremos criando um useState
const UserProfile = () => {
const [userInfo, setUserInfo] = useState<Seller>();
const [loading, setLoading] = useState(true);
Iremos agora chamar a função para exibir as informações do usuário
const UserProfile = () => {
const [userInfo, setUserInfo] = useState<User>({} as User);
const [loading, setLoading] = useState(true);
const { logout } = useAuth();
const handleUserInfos = async () => {
const { data } = await profileService.getUserProfile();
setUserInfo(data);
setLoading(false);
};
useEffect(() => {
handleUserInfos();
}, []);
Vamos agora fazer o loading funcionar aqui
return (
<>
{!loading ? (
<>
<Container
contentContainerStyle={{
paddingBottom: 120,
}}
>
<DefaultTitle title="MEU PERFIL" fontSize={20} />
<ProfileInfo />
<Form />
<UserAds products={Data} seller={false} />
<LogOutButton
onPress={() => {
logout();
}}
>
<LogOutText>Sair da sua conta</LogOutText>
</LogOutButton>
<DeleteAccount
onPress={() => {
Alert.alert(
"Você tem certeza?",
"Ao fazer isso você deleterá a sua conta permanentemente",
[
{
text: "Sim",
onPress: () => {
Alert.alert("Você deletou a sua conta!");
},
},
{
text: "Não",
},
]
);
}}
>
Excluir conta
</DeleteAccount>
</Container>
<NavBar />
</>
) : (
<Loader />
)}
</>
);
Agora, tanto para o ProfileInfo quanto para o form nós vamos passar como props o userInfo
<ProfileInfo userInfo={userInfo} />
<Form userInfo={userInfo} />
Vamos modificar tudo então em ProfileInfo que temos
interface Props {
userInfo: User;
}
const ProfileInfo = ({ userInfo }: Props) => {
Agora, vamos alterar todos os campos aqui em profileInfo
const ProfileInfo = ({ userInfo }: Props) => {
const navigation = useNavigation<PropsStack>();
const { token } = useAuth();
const Rate = userInfo.averageRating;
return (
<>
<Container>
<PrincipalInfoContainer>
<NamePhoneContainer>
<Name>{userInfo.name}</Name>
<Phone>{userInfo.phone}</Phone>
</NamePhoneContainer>
{!Rate ? (
<DefaultText
onPress={() => {
token === null
? navigation.navigate("Login")
: navigation.navigate("Feedback");
}}
>
Sem Avaliações
</DefaultText>
) : (
<Button
onPress={() => {
token === null
? navigation.navigate("Login")
: navigation.navigate("Feedback");
}}
>
<AirbnbRating
selectedColor="#5F96ED"
showRating={false}
isDisabled={true}
size={16}
defaultRating={Rate}
starContainerStyle={{
paddingTop: 4,
}}
/>
</Button>
)}
</PrincipalInfoContainer>
<DefaultText>Usuário desde {getDate(userInfo.createdAt)}</DefaultText>
<DefaultText>
{userInfo.products.length.toString().padStart(2, "0")} anúncios ativos
</DefaultText>
</Container>
<Hr />
</>
);
};
E só vamos precisar adicionar agora nas entidades o tipo para products, que não temos por enquanto
export interface User {
_id: string;
name: string;
email: string;
phone: string;
createdAt: string;
addresses: Address[];
averageRating: number | null;
favorites: string[];
products: Product[];
}