简体   繁体   中英

Unable to fetch html content in vercel server using React

I am working with Reactjs and using nextjs framework,Html content(description_front) is showing data fine in localhost Here is api response (console)

Object
id: "55"
description_front: "<h3><strong>The crypto revolution and its effects</strong></h3>"

but whenever I am trying to display ,"html" content in server(vercel) via api, i am getting following data in my console,But whenever i am trying to display "description_front" in web page i am getting following error

Cannot read properties of undefined (reading 'description_front')

Here is my code, where i am wrong ?

import Axios from "axios";
import  {useRouter}  from "next/router";
const Post = ({ post }) => {
  const router = useRouter();
  const htmlString = post.description_front;
  return (
    <>
    <div className="product-des" dangerouslySetInnerHTML={{ __html: htmlString }} />
    <>
    );
  };

When fetching data from localhost, the fetching is probably very quick, means that the data will be fetched even before the page render will be completed, and the original code will work as supposed.

But when fetching from a remote server, it takes more time, so the rendering process will be done before the data is fetched, and post.description_front will be null, what's causing this error.

The solution will be to check if the value is null before rendering, so a one liner will be: const htmlString = post?.description_front instead of const htmlString = post.description_front

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM