S
SolidJS4mo ago
Karl

Struggling to understand the correct way to use createResource with a store

I have a global store export const [dataStore, setDataStore] = createStore({ some: "data"}) , which should get populated with data fetched from my api. In one of my components i want to automatically renavigate to another url if there is an error from the fetch request as the component cant be displayed correctly. For this i wrote this:
const [data, setData] = createResource<any, any>(fetchData)

createEffect(() => {

if(data.error){
navigate('/devices')
}

setDataStore(data())

})
const [data, setData] = createResource<any, any>(fetchData)

createEffect(() => {

if(data.error){
navigate('/devices')
}

setDataStore(data())

})
return(
<Show when={!data.loading}>
<myComponent/>
</Show>
)
return(
<Show when={!data.loading}>
<myComponent/>
</Show>
)
I realize i shouldnt use setDataStore in the createEffect(). What is the correct way to: 1. wait for the response from createResource() and display the component on success or renavigate on failure 2. populate the dataStore with the data returned from the request after createResource was succesful
7 Replies
Brendonovich
Brendonovich4mo ago
why have both data and dataStore? to answer your questions 1. for loading call data somewhere in your jsx and add a suspense boundary above it, for navigating on failure either do the navigation in the resource getter or as part of the fallback when there's no data available 2. effect is probably fine, you could also call the setter directly in the resource fetcher
Karl
Karl4mo ago
because the data is local to the component but i need the data in other components as well. I tried to do the navigation in the getter but i couldnt use useNavigate(), because it was outside of the component tree. Thank you, i will try Suspense.
Brendonovich
Brendonovich4mo ago
because the data is local to the component but i need the data in other components as well
use cache from @solidjs/router
I tried to do the navigation in the getter but i couldnt use useNavigate()
const navigate = useNavigate();

createResource(() => fetchData().catch(() => navigate(...)))
const navigate = useNavigate();

createResource(() => fetchData().catch(() => navigate(...)))
Neto
Neto4mo ago
Maybe you can use a CatchBoundary as well
Brendonovich
Brendonovich4mo ago
I don't think an error boundary is as useful here since the idea is to do logic on error, rather than show error ui
Neto
Neto4mo ago
fair point
Karl
Karl4mo ago
it works now thank you !
Want results from more Discord servers?
Add your server
More Posts