Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 286
ST80 Avatar asked Sep 21 '25 12:09

ST80


1 Answers

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,
  },
}
like image 81
olgaplaga Avatar answered Sep 23 '25 01:09

olgaplaga