简体   繁体   中英

Nextjs useEffect and useState hook not working on production

In my nextjs -app I use the useEffect and useState -hooks to get some data:

export default function PricingBlock({ data }) {
  const [pricingItems, setPricingItems] = useState()
  const [featuredItem, setFeaturedItem] = useState()

  useEffect(() => {
    const getPricingItems = async () => {
      const pricingItems = await request({ query: PRICING, variables: {} })
      const items = await pricingItems?.allSpecialistPages
      const featured = pricingItems?.specialistLandingpage?.card[0]
      setPricingItems(items)
      setFeaturedItem(featured)
   }
    getPricingItems()
  }, [featuredItem, pricingItems])

 return (
   <div>
     <div
       style={{
         backgroundColor: featuredItem?.backgroundColor?.hex,
         backgroundImage: `url(${featuredItem?.backgroundImage?.url})`,
         borderTop: '1px solid ' + featuredItem?.backgroundColor?.hex,
         borderLeft: '1px solid ' + featuredItem?.backgroundColor?.hex,
         borderRight: '1px solid ' + featuredItem?.backgroundColor?.hex,
       }}
     > ... </div>
   </div>
 )
}

when I run this locally, it works fine, but when I run npm run build - I get the error Object is possibly 'undefined'. referring to featuredItem

I also tried to do:

const [featuredItem, setFeaturedItem] = useState({}) - as an object

but then I get the error Property 'backgroundColor' does not exist on type '{}'.

How can I solve this? Can someone help me out?

This is due to the TypeScript error. This code:

const [featuredItem, setFeaturedItem] = useState()

Does not define the type of featuredItem , so it does not have the first accessed property ( backgroundColor ).

Either fix it, or in your next.config.js , temporarily add the following:

module.exports = {
  ...
  typescript: {
    ignoreBuildErrors: true,
  },
}

Pretty sure this will solve it:

interface FeaturedItem {
    backgroundColor: string;
    //other props if needed...
}
const [featuredItem, setFeaturedItem] = useState<FeaturedItem>();
  • without the generic on useState , typescript assign featuredItem as undefined

If not using Typescript you could try giving featuredItem state a default value.

const defaultValue = {
  backgroundColor: {
    url: '',
    hex: ''
  },
  backgroundImage: ''
};
const [featuredItem, setFeaturedItem] = useState(defaultValue)

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