T
TanStack4y ago
foreign-sapphire

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?
const [selectedCountry, setSelectedCountry] = useState(!isLoading && labels[3]?.label);
const [selectedCountry, setSelectedCountry] = useState(!isLoading && labels[3]?.label);
No description
12 Replies
foreign-sapphire
foreign-sapphire4y ago
you might look at initialState and placeholderData fields of useQuery
foreign-sapphire
foreign-sapphireOP4y 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
xenial-black4y ago
Hi could you provide a codesandbox with a minimal reproduction usecase we could discuss about?
foreign-sapphire
foreign-sapphireOP4y ago
not sure if I could reproduce this, since I am running locally, but I can explain a bit and show some code
foreign-sapphire
foreign-sapphireOP4y ago
No description
foreign-sapphire
foreign-sapphireOP4y 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
adverse-sapphire4y ago
you can always create a reproduction in codesandbox - just replace real fetches with Promise.resolve(someMockJsonData) .
xenial-black
xenial-black4y 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.
// in a parent component
const query = useGetSignupLocaions(router.locale);

if (!query.data) {
return <Loading /> // or null;
);

return <SignupForm initialValue={query.data} />
// in a parent component
const query = useGetSignupLocaions(router.locale);

if (!query.data) {
return <Loading /> // or null;
);

return <SignupForm initialValue={query.data} />
foreign-sapphire
foreign-sapphireOP4y 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
xenial-black4y 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-sapphire
foreign-sapphireOP4y ago
yeah, that's what I thought, so I guess the only way would be with that useEffect running

Did you find this page helpful?