#unable to fetch data using Suspense and Await

1 messages · Page 1 of 1 (latest)

full tinsel
#

Hi,
Im using dataLoaders in my react application. When i simply use loader function and useLoderData function, im able to fetch the data. However, there is some delay in fetching the data so i want to defer the loader using Suspense and Await.

When is use this i only get some Reponse object.

here is my code:

import React, { Suspense } from "react";
import { getBookmarks } from "./api";
import { useLoaderData, defer, Await } from "react-router-dom";
export function loader() {
return defer({ bookmarks: getBookmarks() });
}
export default function Home() {
const dataPromise = useLoaderData();
function renderBookMarks(bookmarks) {
console.log(bookmarks);
}
return (
<div>
<h2>Welcome to bookmarks</h2>
<Suspense fallback={<h2>Loading...</h2>}>
<Await resolve={dataPromise.bookmarks}>
{renderBookMarks}
</Await>
</Suspense>
</div>)
}

my api.js is
import config from './config'

const apiUrl = config.apiUrl;
const apiPort = config.apiPort;
const joinUrl = (baseUrl, url)=>{
return ${baseUrl}/${url}
}
const domain = ${apiUrl}:${apiPort}/api/bookmarks;

export async function getBookmarks(url=""){
url = joinUrl(domain,url)
const data = await fetch(url);
return data;
}

tiny valley
#

I don’t know much way, but the useMatches one works really good for that.

`const [root] = useMatches () ;
return
< Suspense fallback= {<CartLoading />}>
<Await resolve={root.data.cart_and_tokens}>

(cart_and_tokens =>

return (

<Cart
cart={cart_and_tokens.cart}
//…
`

thorny turtle
#

defer does not unwrap responses automatically, you need to do that and resolve the promise with the data itself