I’m trying to fetch new notifications when my component is created, but the response data is empty. However, when I trigger the same logic with a button click, the API returns the correct data.
Here’s part of my Vue.js component:
export default {
data() {
return {
showNotification: true,
notificationsQueue: [],
currentNotification: null
}
},
created() {
this.checkForNotifications()
},
methods: {checkForNotifications() {
console.log('call hook')
this.$http.get('/notifications/').then(response => {
console.log('This should succeed from hook', response)
console.log('This should succeed from hook', response.data)
this.notificationsQueue = response.data
this.showNextNotification()
})
.catch(error => {
console.error('Error captured:', error)
})
},
...
Here’s the output from the console.log() when the request is made in the created hook:
This should succeed from hook [{…}]length: 0[[Prototype]]: Array(0)
However, when I make the same request by clicking a button, the response data is correct:
<button @click="getNotif">Get new notifi</button>
getNotif() {
this.$http.get('/notifications/').then(response => {
console.log('This should succeed', response.data)
})
.catch(error => {
console.error('Error captured:', error)
})
}
Here’s the console.log() output from the button click:
This should succeed [{…}]0: {id: 2, message: 'test first notification', created_at: '2024-08-29 07:48'}length: 1[[Prototype]]: Array(0)
On the Django side, the API seems to work fine:
class BusinessNotificationView(APIView):
permission_classes = [IsAuthenticated]
serializer_class = NotificationSerializer
def get(self, request, *args, **kwargs):
notifications = Notification.objects.filter(user=request.user, is_read=False)
serializer = self.serializer_class(notifications, many=True)
print('return : ', serializer.data)
return Response(serializer.data, status=status.HTTP_200_OK)
And the Django console output:
return : [{'id': 2, 'message': 'test first notification', 'created_at': '2024-08-29 07:48'}]
Why is the created hook returning an empty array while the button click fetches the correct data?
Any ideas on what might be causing this behavior?