Home > Software engineering >  Nextjs useEffect and useState hook not working on production
Nextjs useEffect and useState hook not working on production

Time:12-22

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?

CodePudding user response:

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,
  },
}

CodePudding user response:

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

CodePudding user response:

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

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