I am trying to use useFetch in my page component, so when I navigate to this page using nuxt-link the useFetch will send the request and get the response of 200, but the items fetched from the api won't be shown in the DOM, but if I reload the page everything is working right.
<template>
<section class="container">
<BreadCrumb />
<h1 class="title">{{ brand }}</h1>
<div class="models-container">
<Model
v-for="model in models"
:name="model.model"
:image="model.image"
@click="handleClick(model.model)"
/>
</div>
</section>
</template>
<script setup>
import axios from "axios";
import issue from "~/utils/Encrypt.util";
const router = useRouter();
const { brand } = useRoute().params;
const models = ref([]);
const authToken = useCookie("Authorization-Token");
if (authToken.value) {
const { data: tempModels } = useFetch(
`${import.meta.env.VITE_API_BASE_URL}/v1/vehicles/search`,
{
method: "POST",
body: {
filters: [
{
column_name: "manufacture",
operand: "IsEqualTo",
value: brand,
},
{
column_name: "is_deleted",
operand: "IsEqualTo",
value: 0,
},
],
},
headers: {
"Client-Token": import.meta.env.VITE_API_CLIENT_TOKEN,
"Authorization-Token": authToken.value,
},
}
);
models.value = tempModels.value?.value.vehicles;
}
onMounted(() => {
if (!authToken.value) {
issue().then((token) => {
authToken.value = token["Authorization-Token"];
axios
.post(
`${import.meta.env.VITE_API_BASE_URL}/v1/vehicles/search`,
{
filters: [
{
column_name: "manufacture",
operand: "IsEqualTo",
value: brand,
},
{
column_name: "is_deleted",
operand: "IsEqualTo",
value: 0,
},
],
},
{
headers: {
"Client-Token": import.meta.env.VITE_API_CLIENT_TOKEN,
"Authorization-Token": authToken.value,
},
}
)
.then((res) => {
models.value = res.data.value.vehicles;
});
});
}
});
function handleClick(model) {
router.push(`/vehicles/${brand}/${model}`);
}
</script>
<style scoped lang="scss">
.title {
font-size: 24px;
text-align: center;
margin-bottom: 24px;
}
.models-container {
display: grid;
grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
grid-gap: 1rem;
justify-content: space-between;
}
</style>
I am trying to save some data in the cookies and if the user has no Authorization-Token, one will be made for him and will be set in the cookies and I can use it in my request.
I'm new to SSR and I don't know how can I handle sending the token with my requests and also I don't know how reactive variables made with ref will work in SSR applications.
I tried changing the <nuxt-link>
tag to <a>
tags or navigation using useRouter but it has no difference.
By the way, I replaced the useFetch with the combination of useAsyncData and $fetch.
if (authToken.value) {
await useAsyncData(async () => {
try {
const response = await $fetch(
...
)
} catch {
.