Problems using useQuery inside a Context
I'm pretty new to React so please forgive me if what I am asking is obvious to most of you.
This is the context (very simplified):
- I have several tables of related elements, organized in a hierarchical way (see example below)
- I have a navBar on which I can select a Main object from a list. Selecting an Item gives me its ID
- In my main page, I want to display the different components of a Main object (referenced by the previously selected ID),
- therefore, I need to gather this data from the database (ie: the Main object, the Country referenced by the
countryId
and the cities references by the cityIds[]
)
Since I will need to use several Components to display everything, I don't want to be passing props all along and need to create a Context that wraps my page, to provide access to all the necessary info in one place.
However, although the mainId wouldn't change, its countryId could change. How would I detect this change in my context and re-query the planet data for the same Main object?6 Replies
Hello @patochem ,
what i would do is create the Context and use it like this:
in the Main component
then i would set up a useState, same in the Main compoennt liek this:
Then, in the child component where you would normally use the countryId, import the e.g. CountryContext, destructure it like:
then in a useEffect watch for countrId changes and call your Convex mutations or queries, whicevrer you need inside the useEffect based on the countryId cahnges.
Hope that helps!
Thanks for answering @StoicWanderer
This was my first thought but it doesn't work because you can't use "useQuery" inside useEffect, since it's a hook
React Hook "useQuery" cannot be called inside a callback. React Hooks must be called in a React function component or a custom React Hook function.eslintreact-hooks/rules-of-hooks
It's easier than you think, use only the countryId in the useEffect hook to check for changes and call your useState setter function inside as well, then outside of the useEffect write a conditional check whether your state changed call the useQuery, i think, but you could use a setInterval to check periodically
could you give an quick example of the first option, please?
How would I detect this change in my context and re-query the planet data for the same Main object?Presumably a React state change causes the update to the Context, also causing all children to rerender. As long as you don't memoize in between, the whole tree will rerender, including your
useQuery
calls that consume values from the React context.
I would avoid useEffect if you can.Yep, that's what is happening... I don't have anything to do
Looks like magic actually!
Thanks @Michal Srb !