5

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
    }
}
Mike
  • 125
  • 2
  • 2
  • 8

6 Answers6

1

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.

Sabari S
  • 11
  • 1
  • As it’s currently written, your answer is unclear. Please [edit] to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 18 '23 at 07:45
0

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.

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.
0

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

0

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

  • 3
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 21 '22 at 21:23
0

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

Dmitriy
  • 1
  • 1
  • 1
    Your answer could be improved with additional supporting information. Please [edit] to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers [in the help center](/help/how-to-answer). – Community Aug 21 '22 at 21:34