React query populate initial state
Hello all, I have a question I am trying to populate a state when the component first renders, using react-query. I am able to do it using useEffect, but wondering if there's a way to do it without it. currently I have something like this, I have also tried something like this as well. Maybe I am missing something basic?

12 Replies
foreign-sapphire•4y ago
you might look at initialState and placeholderData fields of useQuery
foreign-sapphireOP•4y ago
I am not sure if this would work, this data is being fetch from a cms for some fields so there's no previous cache or initial data that I could use
xenial-black•4y ago
Hi could you provide a codesandbox with a minimal reproduction usecase we could discuss about?
foreign-sapphireOP•4y ago
not sure if I could reproduce this, since I am running locally, but I can explain a bit and show some code
foreign-sapphireOP•4y ago

foreign-sapphireOP•4y ago
so this is my fetch data, query and this will fetch translation, I want to add a default to selectedCountry, without using the useEffect hook, this works fine the way I have it, Just wondering if its possible to do it withouit
adverse-sapphire•4y ago
you can always create a reproduction in codesandbox - just replace real fetches with
Promise.resolve(someMockJsonData) .xenial-black•4y ago
The way I usually like to do this is hold off on rendering the component that needs the initial data until it's ready.
foreign-sapphireOP•4y ago
I have something like this https://codesandbox.io/s/adoring-hypatia-dmtohy?file=/src/component.js so what I am trying to do again, is just have a initial value without depending on the useEffect
enyelsequeira
CodeSandbox
adoring-hypatia-dmtohy - CodeSandbox
adoring-hypatia-dmtohy by enyelsequeira using @tanstack/react-query, react, react-dom, react-scripts
xenial-black•4y ago
Hi, this would be the case only if you already have cached data I think. Meaning the query used in
useGetData was already run.foreign-sapphireOP•4y ago
yeah, that's what I thought, so I guess the only way would be with that useEffect running
xenial-black•4y ago