joschan21 / nextjs-realtime-chat

A performant and reliable realtime-chat-app built with NextJS 13
939 stars 162 forks source link

#Fixed "Error: "undefined" is not valid JSON" in "/src/app/dashboard/page.tsx" #19

Open Bishwarup-Das opened 4 months ago

Bishwarup-Das commented 4 months ago

This error indicates that the lastMessageRaw variable is undefined and thus cannot be parsed by JSON.parse.

To handle cases where lastMessageRaw might be undefined or invalid JSON, you should add error handling when parsing lastMessageRaw.

Approach to handle the errors.

1. Check if lastMessageRaw is defined.

2. Wrap the JSON.parse call in a try-catch block to handle any potential errors during parsing.

      if (lastMessageRaw) {
        try {
          lastMessage = JSON.parse(lastMessageRaw) as Message
        } catch (error) {
          console.error("Error parsing lastMessageRaw:", error)
        }
      }

      return {
        ...friend,
        lastMessage: lastMessage || { text: '', senderId: '' }, // Provide default values if needed
      }

This code ensures that if lastMessageRaw is undefined or invalid, the application will not crash and will handle the situation gracefully by providing default values.