codingforthemoment
codingforthemoment

Reputation: 135

Application error: a client-side exception has occurred (see the browser console for more information)

Nextjs Blog App

Currently seeing: Application error: a client-side exception has occurred (see the browser console for more information). I see the above error when creating a post in deployment on AWS Amplify console and DynamoDB is unable to redirect to post created on submit but I can view the post locally on submit. The errors only appears once deployed to DynamoDB.

Any indications on why this may be occurring is much appreciated.

enter image description here

///create-post.js
import { withAuthenticator } from '@aws-amplify/ui-react'
import { useState, useRef } from 'react'
import { API, Storage } from 'aws-amplify'
import { v4 as uuid } from 'uuid'
import { useRouter } from 'next/router'
import SimpleMDE from "react-simplemde-editor"
import "easymde/dist/easymde.min.css"
import { createPost } from '../graphql/mutations'
import MySelect from '../components/Autocomplete'
import { useForm } from "react-hook-form";
import { ErrorMessage } from '@hookform/error-message';
import DatePicker from "react-datepicker";
import "react-datepicker/dist/react-datepicker.css";


const initialState = { title: '', content: '', category: '', countries: '', select: '', date: '', createdAt: new Date().toISOString()}

function CreatePost() {
  const [startDate, setStartDate] = useState(new Date());

  const { register, handleSubmit, formState: { errors } } = useForm();
  const onSubmit = data => console.log(data);

  const [post, setPost, state] = useState(initialState)
  const hiddenFileInput = useRef(null);
  const { title, content, category, countries, select, date,  createdAt } = post

  const router = useRouter()
  function onChange(e) {
    setPost(() => ({ ...post, [e.target.name]: e.target.value }))
  }
  
  console.log('setPost', post.countries ? countries.label : "")
  async function createNewPost() {
    if ( !title || !content || !category || !countries || !select || !date ||  !createdAt ) return
    const id = uuid() 
    post.id = id
    await API.graphql({
      query: createPost,
      variables: { input: post },
      authMode: "AMAZON_COGNITO_USER_POOLS"
    })
    router.push(`/posts/${id}`)
    
  }
  return (
    <form onSubmit={handleSubmit(onSubmit)} autoComplete="false"
      noValidate>
    <div>
      <h1 className="text-3xl font-semibold tracking-wide mt-36">Create New Article</h1>
      <p className="mt-6">Enter Title: </p>
      <input
        aria-invalid={errors.title ? "true" : "false"}
        {...register('title', { required: true })}
        onChange={onChange}
        name="title"
        placeholder="Title"
        value={post.title}
        className="border-b pb-2 text-lg my-4 focus:outline-none w-full font-light text-gray-500 placeholder-gray-500 y-2"
        
      />
      {errors.title && (
        <span role="alert" className="mb-4 mt-4 alert">
          This field is required
        </span>
      )}
      <p>Enter Category: </p>
      <input
        aria-invalid={errors.category ? "true" : "false"}
        {...register('category', { required: true })}
        onChange={onChange}
        name="category"
        placeholder="Author Category"
        value={post.category}
        className="mb-4 mt-4 border-b pb-2 text-lg my-4 focus:outline-none w-full font-light text-gray-500 placeholder-gray-500 y-2"
      />
      {errors.category && (
        <span role="alert" className=" alert">
          This field is required
        </span>
      )}
      <p  className="mb-2 mt-2" >Select Created Date: </p>
      <DatePicker
        aria-invalid={errors.date ? "true" : "false"}
        {...register('date', { required: true })}
        selected={post.date}
        onChange={(date) => setPost({...post, date})}
        name="date"
        placeholder="Created date" autoComplete="true"
        className="visible focus:outline-black outline-black"
        
      />
      {errors.date && (
        <span role="alert" className="mb-12 mt-12 alert">
          This field is required
        </span>
      )}
      <div className="mb-2 mt-2">
      <p>Select Author&apos;s Country:</p>
      <MySelect
        aria-invalid={errors.countries ? "true" : "false"}
          {...register('countries', { required: true })}
          options={options}
          name="countries"
          onChange={onChange => setPost({ ...post, countries: onChange.value })}
          value= {post.countries}
          className="m-6"
          placeholder="Countries Select..."
        />
        </div>
        <div className="ml-6 alert">
      {errors.countries && (
        <span role="alert" className="mb-12 mt-12 alert">
          This field is required
        </span>
      )}
      </div>
      <div className="mb-2 mt-2">
      <p>Select Blog&apos;s Category</p>
      <MySelect
        aria-invalid={errors.select ? "true" : "false"}
          {...register('select', { required: true })}
          options={selectCategoryOptions}
          name="select"
          onChange={onChange => setPost({ ...post, select: onChange.label})}
          value= {post.select}
          className="m-6"
          placeholder="select Select..."
        />
        </div>
        <div className="ml-6 alert">
      {errors.select && (
        <span role="alert" className="mb-12 mt-12 alert">
          This field is required
        </span>
      )}
      </div>
      <div className="mb-2 mt-2">
      </div>
        <p className="mt-8" >Enter Blog Content: </p>
      <SimpleMDE 
          aria-invalid={errors.content ? "true" : "false"}
            {...register('content', { required: true })}
          value={post.content} 
          onChange={value => setPost({ ...post, content: value })} 
          />
      {errors.content && (
        <span role="alert"  className="mb-4 mt-4 alert">
          This field is required
            <br/>
            <p className="alert font-semibold"> 
          Please check all fields are filled in  & wait 3 seconds before refreshing the page
          </p> 
          </span>
      )}
      <input
        onChange={onChange}
        name="createdAt"
        placeholder="Time created"
        value={post.createdAt}
        className="invisible"
        
      />
      <br/>
      
      <button
        type="submit"
        className="mb-4 mt-4 bg-blue-600 text-white font-semibold px-8 py-2 rounded-lg"
        onClick={createNewPost}
      >Save Article</button>
    </div>
    </form>
  )
}
const selectCategoryOptions  = [
  {
    label: "Sport"
  },
  {
    label: "News"
  },
  {
    label: "Weather"
  },
  {
    label: "Other"
  }
];
const options = [
  { label: 'Africa', value: 'Africa' },
  { label: 'USA', value: 'USA' },
  { label: 'Asia', value: 'Asia' },
  { label: 'Europe', value: 'Europe' },
  { label: 'Oceania', value: 'Oceania' },
]

export default withAuthenticator(CreatePost)
//pages/posts/[id].js
import { API, Storage } from 'aws-amplify'
import { useState, useEffect } from 'react'
import { useRouter } from 'next/router'
import ReactMarkdown from 'react-markdown'
import { listPosts, getPost } from '../../graphql/queries'

export default function Post({ post }) {
    const router = useRouter()
    if (router.isFallback) {
        return <div>Loading...</div>
    }
    return (
        <div>
        <h1 className="text-5xl mt-4 font-semibold tracking-wide mt-36 text-center">Title: {post.title}</h1>
        <h4 className="text-3xl mt-4 font-semibold tracking-wide text-center">Category: {post.category}</h4>
        <p className="text-1xl mt-4 font-semibold tracking-wide text-center">Selected Category Name: {post.select }</p>
        <div className="m-8 text-center">
            Content: <ReactMarkdown className='prose text-center' >{post.content}</ReactMarkdown>
        </div>
        <time dateTime={post.createdAt} className="invisible">
                Blog gerenated date created at: {new Date(post.createdAt).toDateString()}</time>
                <br/>
        <time dateTime={post.date} className="text-center">
        User date created at: {new Date(post.date).toDateString()}</time>
        <p className="text-1xl mt-4 font-semibold tracking-wide">Author&apos;s Country: {post.countries }</p>
        <p className="text-sm font-semibold my-4">Author:  {post.username}</p>
        </div>
    )
    }

    export async function getStaticPaths() {
    const postData = await API.graphql({
        query: listPosts
    })
    const paths = postData.data.listPosts.items.map(post => ({ params: { id: post.id }}))
    return {
        paths,
        fallback: true
    }
    }

    export async function getStaticProps ({ params }) {
    const { id } = params
    const postData = await API.graphql({
        query: getPost, variables: { id }
    })
    return {
        props: {
            post: postData.data.getPost
        },
        revalidate: 60
    }
}

Upvotes: 5

Views: 53691

Answers (8)

Ganang Wahyu W
Ganang Wahyu W

Reputation: 59

i get same this error, i was solve this with make sure the data input is correct because any special char "/" or ">" conflict with html syntax. i hope helping you

Upvotes: 0

Faizan Ali
Faizan Ali

Reputation: 1

It appears there may be a syntax error in your code. The code successfully builds during development, but in production mode, when the API is called, there seems to be an issue with how the data is being processed, potentially using an incorrect method.

Upvotes: 0

Sabari S
Sabari S

Reputation: 9

From this Error I have tried solution which i have removed all head tag it included link, meta tag which removed all pages, then got the actual output.

Upvotes: 0

Dmitriy
Dmitriy

Reputation: 1

I solved this problem by removing unnecessary imports at the beginning of the document

Upvotes: 0

Tejovardhan C V
Tejovardhan C V

Reputation: 1

we have the same issue, fixed by removing autofocus for MUI buttons in the whole application.

Upvotes: 0

Chidimma Nworah
Chidimma Nworah

Reputation: 315

Make sure you have all links in the head containing the word crossorigin spelt correctly like this **crossOrigin **

Upvotes: 0

I was trying to open the MUI Page and I got that error and

  1. I found a temporary solution on an internet blog that was to open the page in an incognito window
  2. The definitive solution and without the need to open the incognito window was to delete the cookies from the page by clicking on the padlock that appears in the browser's search box, select the cookies option and then click the remove button and reload the page.

Upvotes: 0

chaudhary subash
chaudhary subash

Reputation: 1

In your pages/blog/[id].js file, you need to add the following

//pages/posts/[id].js
import { API, Storage } from 'aws-amplify'
import { useState, useEffect } from 'react'
import { useRouter } from 'next/router'
import ReactMarkdown from 'react-markdown'
import { listPosts, getPost } from '../../graphql/queries'
import Error404 from '../../components/Error404'

export default function Post({ post }) {
    const router = useRouter()


    //Add this
      if (!router.isFallback && !post?.title) {
          return <Error404 />;
      }

    return (
    //Also add this
        {router.isFallback? (<div>Loading...</div>)
        : (<div>
            <h1 className="text-5xl mt-4 font-semibold tracking-wide mt-36 text-center">Title: {post.title}</h1>
            <h4 className="text-3xl mt-4 font-semibold tracking-wide text-center">Category: {post.category}</h4>
            <p className="text-1xl mt-4 font-semibold tracking-wide text-center">Selected Category Name: {post.select }</p>
            <div className="m-8 text-center">
            Content: <ReactMarkdown className='prose text-center' >{post.content}</ReactMarkdown>
            </div>
            <time dateTime={post.createdAt} className="invisible">
                Blog gerenated date created at: {new Date(post.createdAt).toDateString()}</time>
            <br/>
            <time dateTime={post.date} className="text-center">
                 User date created at: {new Date(post.date).toDateString()} 
            </time>
            <p className="text-1xl mt-4 font-semibold tracking-wide">Author&apos;s Country: {post.countries }</p>
            <p className="text-sm font-semibold my-4">Author:  {post.username}</p>
        </div>)
        }
    )
    }

    export async function getStaticPaths() {
    const postData = await API.graphql({
        query: listPosts
    })
    const paths = postData.data.listPosts.items.map(post => ({ params: { id: post.id }}))
    return {
        paths,
        fallback: true
    }
    }

    export async function getStaticProps ({ params }) {
    const { id } = params
    const postData = await API.graphql({
        query: getPost, variables: { id }
    })
    return {
        props: {
            post: postData.data.getPost
        },
        revalidate: 60
    }
}

I don't know it will work for you or not. But I have also encountered same error. The above code configuration has fixed the error in my case.

Upvotes: 0

Related Questions