Deconstructing data from the promise object from useLoaderData hook - react router 6
I'm trying out react router 6 and have gotten through with the loader function however need some help with accessing the data within this object
export const loaderHome=()=>{ //console.log('fgfgf')
return defer({
data: loadPosts(null, 1, 12, null)
})
}
This function is working and accessing data from the server. I'm trying to access the data with the useLoaderData hook:
const Home=()=>{
const data=useLoaderData();
console.log(data)
}
Anyone knows how to output the _data or PromiseResult object within the data index of the returned promise?
I tried this but getting undefined:
const {data}= useLoaderData()
console.log(data._data)
I'm seeing this "invoke property getter" when I hover _data:
So I tried accessing the getter property:
const {data}= useLoaderData()
console.log(data._data())
But getting: Uncaught TypeError: data._data is not a function
I'm seeing in the sources tab (chrome) the definition for this promise as:
Object.defineProperty(promise, "_data", { get: () => data });
this.emit(false, key);
return data;
Update: I got it working however I still don't understand what was initially wrong.
I modified the loader to include await:
export const loaderHome=async()=>{ //console.log('fgfgf')
return defer({
data: await loadPosts(null, 1, 12, null)
})
}
But loadPosts also has await so I can't understand why it's returning a complicated object without the await in loaderHome:
const loadPosts=async(e, currentPageNum, filmsPerPage, dispatchDisplayState)=>{
try{
// call node.js to load the films based on the user's selected index if applicable
const result=await fetch(process.env.REACT_APP_NodeURL+'/user/films/'
+currentPageNum+'/'+filmsPerPage,{
method:'GET',
headers:{ 'Content-Type': 'application/json', }
});
if(!result.ok) throw json({message:'node fetching error'},{status:500});
else return(await result.json())
}
catch(err){
console.log('error encountered'+err);
return(err);
}
}
Now when I print in Home, I'm getting the data:
const Home=()=>{
const data=useLoaderData();
console.log(data.films)
}
Without the await the data is still passing to the useLoaderData (From the output pictures above) but I can't extract it. Anyone knows why?
Comments
Post a Comment