"Cannot read property 'data' of null

Hi there,

I'm having some trouble getting my image to render consistently. The problem is that my state is not updating on initial load and stays null, but if i can get it to re-render the image will appear successfully. I've triple checked my component with the docs and all the examples, as well as replaced my api token to make sure I didn't mis-type anything, but I am completely stumped. Any help would be greatly appreciated. :slight_smile:

image code:

function HeaderImage() {

const [doc, setDocData] = useState(null)

useEffect(() => {

    const fetchData = async () => {

        const response = await Client.query(

            Prismic.Predicates.at('document.type', 'landing_image')

        ).catch(console.error)

        if(response) {

            setDocData(response.results[0])

        }

    }

    fetchData()

}, [])



return(

    <header>

        <NavMenu />

        <img src={doc.data.header_image.url} alt={doc.data.header_image.alt} className='header-image'/>

    </header>

)

}

export default HeaderImage

Hello @josh,

Thank you for reaching out to me.

Can you try to add if check before return to see if doc is not null, something like that:

if(doc)
  return(
     ...........
  )
)

It will check doc before rendering because usually, useEffect runs after rendering.

Let me know if that does not solve the issue.

Thanks,
Priyanka

Thanks so much, this did help the issue!

Hello Josh,

I'm glad that it's working for you. Don't hesitate to reach out to us if you have any questions.

Thanks,
Priyanka

This topic was automatically closed 24 hours after the last reply. New replies are no longer allowed.