Promise is fulfilling as undefined

I have a component that fetches all the terms of a taxonomy product_type to be displayed on the frontend (WordPress site). Terms are fetched via REST and terms (may) contain a url to a svg file that I wish to directly embedded in the DOM for manipulation. Assumes all SVG files are trusted. fetchSVG() takes in the svg url and returns the <SVG> markup. The problem is await fetchSVG doesn't await at all... the promise immediately resolves to 'undefined' Any help understanding whats wrong would be lovely
useEffect(() => {
const fetchData = async () => {
try {
const termsResponse = await axios.get('/wp-json/wp/v2/product_type');

const terms = termsResponse.data.map((term) => {
if (term.title_svg_url) {
console.log("Fetching!",term.title_svg_url);
const svgContent = fetchSVG(term.title_svg_url);
console.log('svgContent (Promise)',svgContent);
term.title_svg_url = svgContent;
}
console.log('returning term',term);
return term;
});
console.log(terms);
setTerms(Promise.all(terms));

} catch (e) {
console.error('Terms[]:', e);
}
};

fetchData();
}, []);

const fetchSVG = async (svg_url) => {
axios.get(svg_url)
.then((res)=>{
console.log('fetchSVG',res);
return res.data;
})
.catch((e)=>{
console.log('fetchSVG',e);
})
}
useEffect(() => {
const fetchData = async () => {
try {
const termsResponse = await axios.get('/wp-json/wp/v2/product_type');

const terms = termsResponse.data.map((term) => {
if (term.title_svg_url) {
console.log("Fetching!",term.title_svg_url);
const svgContent = fetchSVG(term.title_svg_url);
console.log('svgContent (Promise)',svgContent);
term.title_svg_url = svgContent;
}
console.log('returning term',term);
return term;
});
console.log(terms);
setTerms(Promise.all(terms));

} catch (e) {
console.error('Terms[]:', e);
}
};

fetchData();
}, []);

const fetchSVG = async (svg_url) => {
axios.get(svg_url)
.then((res)=>{
console.log('fetchSVG',res);
return res.data;
})
.catch((e)=>{
console.log('fetchSVG',e);
})
}
console.log : Fetching! http://pilgrimsusa.local/wp-content/uploads/2024/03/pilgrims_logo.svg : svgContent (Promise) Promise {<fulfilled>: undefined} ...later : fetchSVG {data: '<?xml version="1.0" encoding="UTF-8"?>\n<svg xmlns=…ar(--second); stroke-width: 0px;"></path>\n</svg>\n', status: 200, statusText: 'OK', headers: {…}, config: {…}, …}
1 Reply
fluffy bacon
fluffy baconOP9mo ago
Well, I got it to work, but I would be lying if I understood why. I have to return the <SVG> explicitly outside of the axios statement. why???? 😢 const fetchSVG = (svg_url) => { const value = axios.get(svg_url) .then((res)=>{ console.log('fetchSVG',res); return res.data; }) .catch((e)=>{ console.log('fetchSVG',e); }) return value; }
Want results from more Discord servers?
Add your server