Client side caching problem on srr

Hello guys. I need some help for a project. Problem is caching. Server doesn't aware client's localStorage so it's fetching data again and again even there is valid data in my client.
<script setup>

const cachedData = useLocalStorage('deneme', {
data: null,
timestamp: null
});

console.log(Date.now() - cachedData.value.timestamp);
const { data, refresh } = useAsyncData('deneme', () => {
const currentTime = Date.now();
if (cachedData.value.data && currentTime - cachedData.value.timestamp < 30000) {
console.log(currentTime - cachedData.value.timestamp);
return cachedData.value.data;
}
try {
const freshData = Date.now();

// Update local storage cache
cachedData.value = {
data: freshData,
timestamp: currentTime
};

return freshData;
} catch (error) {
// Fallback to cached data if fetch fails
return cachedData.value.data;
}
});

const clearCache = () => {
cachedData.value = {
data: null,
timestamp: null
};
};
</script>
<script setup>

const cachedData = useLocalStorage('deneme', {
data: null,
timestamp: null
});

console.log(Date.now() - cachedData.value.timestamp);
const { data, refresh } = useAsyncData('deneme', () => {
const currentTime = Date.now();
if (cachedData.value.data && currentTime - cachedData.value.timestamp < 30000) {
console.log(currentTime - cachedData.value.timestamp);
return cachedData.value.data;
}
try {
const freshData = Date.now();

// Update local storage cache
cachedData.value = {
data: freshData,
timestamp: currentTime
};

return freshData;
} catch (error) {
// Fallback to cached data if fetch fails
return cachedData.value.data;
}
});

const clearCache = () => {
cachedData.value = {
data: null,
timestamp: null
};
};
</script>
2 Replies
kapa.ai
kapa.ai4w ago
Hi @Yazılım Panteri. I'm kapa.ai, your friendly support bot. I will try to answer your question by searching through the knowledge base. :wave: ---------------------- The issue you're experiencing is related to the server-side rendering (SSR) nature of Nuxt and how it interacts with client-side caching. Let me explain the problem and suggest a solution based on the provided knowledge sources. The core of the issue is that the server doesn't have access to the client's localStorage, as you correctly pointed out. This means that on every server-side render, the data will be fetched anew, regardless of what's stored in the client's localStorage. To address this, Nuxt 3.8 introduced a new feature called getCachedData for useFetch and useAsyncData composables. This feature can help avoid superfluous calls to an API and cache data for visitors on the client side Nuxt 3.8 - Client-side caching with getCachedData (https://www.youtube.com/watch?v=aQPR0xn-MMk). Here's how you can modify your code to take advantage of this feature:
<script setup>
const { data, refresh } = useAsyncData('deneme',
() => Date.now(), // Your data fetching function
{
getCachedData: () => {
const cachedData = localStorage.getItem('deneme')
if (cachedData) {
const { data, timestamp } = JSON.parse(cachedData)
if (Date.now() - timestamp < 30000) {
return data
}
}
return null
}
}
)

// Update localStorage after successful fetch
watch(data, (newData) => {
if (newData) {
localStorage.setItem('deneme', JSON.stringify({
data: newData,
timestamp: Date.now()
}))
}
})

const clearCache = () => {
localStorage.removeItem('deneme')
refresh()
}
</script>
<script setup>
const { data, refresh } = useAsyncData('deneme',
() => Date.now(), // Your data fetching function
{
getCachedData: () => {
const cachedData = localStorage.getItem('deneme')
if (cachedData) {
const { data, timestamp } = JSON.parse(cachedData)
if (Date.now() - timestamp < 30000) {
return data
}
}
return null
}
}
)

// Update localStorage after successful fetch
watch(data, (newData) => {
if (newData) {
localStorage.setItem('deneme', JSON.stringify({
data: newData,
timestamp: Date.now()
}))
}
})

const clearCache = () => {
localStorage.removeItem('deneme')
refresh()
}
</script>
This approach uses the getCachedData option of useAsyncData to check localStorage before making a request. If valid cached data exists, it's returned immediately. Otherwise, a new request is made. A few key points to note: 1. The getCachedData function is only called on the client side, so you don't need to worry about server-side access to localStorage Docs > Getting-started > Data fetching > Keys (https://nuxt.com/docs/getting-started/data-fetching#keys). 2. The watch function updates localStorage whenever new data is fetched, ensuring the cache stays current. 3. The clearCache function allows you to manually clear the cache and refresh the data. This solution should solve your caching problem while still maintaining the benefits of SSR. It ensures that fresh data is fetched on the server for the initial render, while subsequent client-side navigations can use the cached data when appropriate. Remember that this approach is best suited for data that doesn't change frequently and where a slight delay in updates is acceptable. For more dynamic data, you might need to adjust the caching duration or consider other strategies. ---------------------- Note: you can ask me a follow up question by @ mentioning me again :speech_balloon: ----------------------
kapa.ai
kapa.ai4w ago
<@759827985745969153> Kapa.ai is still learning and improving, please let me know how I did by reacting below.
Want results from more Discord servers?
Add your server