1

I'm using localforage in a custom React hook that is meant to cache and return data. If data already exists, return it. If data doesn't exist, cache it and then return it. Before I was using a synchronous LRU library, but it seems the asynchronous nature of IndexedDB makes this a lot harder.

As of now, the custom hook is returning a promise with a resolved value that I need access to in one of my components. The data is right there, and yet I can't get to it. I've tried a mix of async/await, generators, and SE threads, but I suppose I'll use this snippet to post with.

Here's a condensed version of the component receiving the promise from the custom hook

const Component = ({ match }) => {
    let data = useSuspenseFetch(match.params.id)
        .then(res => {
            console.log('need this', res)
            return res
        })
    console.log('right here', data)

    return <></>
}

export default Component

Is there any way to achieve this? I feel like I've gotten so close so many times, but there's always some pitfall.

  • You have to wait for the promise to resolve, either with async/await, or inside the .then. Store the return value in component state so that your component can use the value when you get the promise result back and set it in state – Andy Ray Dec 07 '19 at 02:32
  • That's hilarious, I actually remember earlier having a mini epiphany and realizing this exact solution, but was so focused on trying to return actual data instead of a promise in the hook that I didn't get around to it in time before my brain had died. I haven't tested this yet, but you're totally correct. Thank you for pointing out my stupidity. I'll prolly have to throw it in a useEffect so it doesn't get re-rendered, but should be cake. *should*.. :) – Nate Osterfeld Dec 07 '19 at 03:29

0 Answers0