Trouble getting images to populate in a Sanity.io application
2 replies
Last updated: Mar 10, 2023
D
Reposting with higher detail, having a problem getting images to populate.my client.js is as follows -
on one page of my application the images work fine, my import statement looks like this -
and my usage -
this works perfectly, no errors or issues, however on another page the same set up doesnt work -
import statement:
Usage:
basically the exact same thing except for this page i get the error -
Im very confused because these items are almost identical and yet i get an error for one and not the other.
is there a better way to import images? is there something im missing entirely. thank you in advance for any help!
import { createClient } from "@sanity/client"; import imageUrlBuilder from "@sanity/image-url"; export const config = { projectId: 'nf98xbc0', dataset: 'production', apiVersion: '2023-03-02', useCdn: true, }; const builder = imageUrlBuilder(config); export const sanityClient = createClient(config); function urlFor(source) { return builder.image(source); } export {urlFor}
const Engineers = () => { const [engineers, setEngineers] = useState([]); useEffect(() => { sanityClient .fetch( `*[_type == "engineers"] | order(name) { name, genres, image{ asset->{ _id, url } } }`) .then((data) => setEngineers(data)) .catch((error) => console.error(error)); }, []);
{engineers.map((engineer) => ( <NavigationCard key={engineer._id}> <NavigationImg src={engineer.image.asset.url} /> <NavigationTitle> {engineer.name} <Genres>{engineer.genres}</Genres> </NavigationTitle> </NavigationCard> ))}
import statement:
const Studios = () => { const [studios, setStudios] = useState([]); useEffect(() => { sanityClient .fetch( `*[_type == "studios"] | order(name) { name, image{ asset->{ _id, url } } }`) .then((data) => setStudios(data)) .catch((error) => console.error(error)); }, []);
{studios.map((studio) => ( <NavigationCard> <NavigationImg src={studios.image.asset.url} /> <NavigationTitle> {studio.name} </NavigationTitle> </NavigationCard> ))}
Uncaught TypeError: Cannot read properties of undefined (reading 'asset')
is there a better way to import images? is there something im missing entirely. thank you in advance for any help!
Mar 10, 2023, 3:53 PM
R
As was pointed out in your previous thread, you’re trying to evaluate an object before the promise has resolved. You either need to check for the existence of the data first or use optional chaining.
Mar 10, 2023, 7:09 PM
D
user M
understood. thank you, im sorry im very new with this, could you please help me with that?Mar 10, 2023, 7:22 PM
Sanity– build remarkable experiences at scale
The Sanity Composable Content Cloud is the headless CMS that treats content as data to power your digital business. Free to get started, and pay-as-you-go on all plans.