should I put useQuery inside a useEffect and should I store returned data in state?
Still wrapping my head around using this library with modern react hooks patterns.
Because data fetching is considered a side effect I've seen this pattern a lot in tutorials and docs.
const [data, setData] = useState([]);
useEffect(() => {
fetch("http://localhost:3001/links/")
.then(response => response.json())
.then(data => setData(data));
},[]);
Should I be doing a similar pattern with this library? ie putting useQuery in useEffect and storing the data returned from useQuery inside useState
Or can I simply just use useQuery as is and directly access the data returned in my components.
Lets assume I'm just building a simple todo app where I want to create, update and delete todo items.
I don't store return data from query to react state. I just feel like that's an anti-pattern. You should just use the returned data as it is like below:
const { loading, data, error } = useQuery(SOME_QUERY)
// If you absolutely need to cache the mutated data you can do the below. But
// most of the time you won't need to use useMemo at all.
const cachedMutatedData = useMemo(() => {
if (loading || error) return null
// mutate data here
return data
}, [loading, error, data])
if (loading) return <Loader />
if (error) return <Error />
// safe to assume data now exist and you can use data.
const mutatedData = (() => {
// if you want to mutate the data for some reason
return data
})()
return <YourComponent data={mutatedData} />
But if you must store the returned data, could do below:
const { loading, data, error } = useQuery(SOME_QUERY)
const [state, setState] = React.useState([])
React.useEffect(() => {
// do some checking here to ensure data exist
if (data) {
// mutate data if you need to
setState(data)
}
}, [data])
Yeah the useQuery should be already an "effect" hook, so you don't have to do that inside useEffect. the useEffect was meant for async stuff, like fetch, but the useQuery is not an async function, it will immediately return result (loading:true, data:null). Then re-return the result when data is ready. so it does not have to be in useEffect.
the useEffect was meant for async stuff
It's meant to perform any side effects from state changes. Async stuff is one use case. Using apollo to fetch data, I rarely use useEffect for async fetching.
Thanks @jinshin1013, useMemo is a nice idea since setting state for mutated data in onCompleted was causing an infinite loop (onCompleted called infinitely)
const { loading, data, error } = useQuery(SOME_QUERY) if (loading) return <Loader /> if (error) return <Error /> // safe to assume data now exist and you can use data. const mutatedData = React.useMemo(() => { // if you want to mutate the data for some reason return data }, [data]) return <YourComponent data={mutatedData} />
React throws compile time error that you can't use useMemo conditionally.
React Hook "useMemo" is called conditionally. React Hooks must be called in the exact same order in every component render. Did you accidentally call a React Hook after an early return?
You are right. No need to use useMemo.
What do you think in the case you have for example 3
So we need need to use 3 interdependent useQuery calls in the same Component.
Do you think in that case will have the sense to use several useEffect?
@JuanmaMenendez I running into this issue myself. Did you find a solution to this or find a better way to structure your queries?
@mmborado there is no need to use useEffect.
You should add the skip property to the dependent useQuery
Example:
//first query
const { data, error, loading } = useQuery(GET_DOGS);
//second query that depends on the first one.
const result2 = useQuery(GET_BREEDS, { skip: !data, variables: { dogId: data && data.dogs[0].id },});
@mmborado @JuanmaMenendez You could always use the apollo client directly and create a custom hook like:
const useCompoundQueries = () => {
// Grab the Apollo client
const client = useApolloClient()
const [data, setData] = useState(null)
const [loading, setLoading] = useState(false)
async function runQuery() {
// Set the loading true.
setLoading(true)
// Manually query your queries.
const query1Result = await client.query({ query: QUERY1 })
const query2Result = await client.query({ query: QUERY2, variables: {...} })
..... rest of the logic
// Reset the loading state.
setLoading(false)
setData(data)
}
// You can either start the query when this gets mounted or manually run it.
useEffect(() => {
// Automatically run the query if you want
runQuery()
}, [query])
return {
loading,
data,
runQuery,
}
}
It's very simplified and haven't tested but you get the idea.
@jinshin1013 honestly I think to use the skip property is much easier and cleaner but it is always good to see different solutions to a problem, thanks for your answer.
But if you must store the returned data, could do below:
const { loading, data, error } = useQuery(SOME_QUERY) const [state, setState] = React.useState([]) React.useEffect(() => { // do some checking here to ensure data exist if (data) { // mutate data if you need to setState(data) } }, [data])
How can use the loading and error variable when I am storing the returned data using useEffect hook?
something like this?
useEffect(() => {
// here, you can use loading and/or error variable, for example:
if(loading === false && data){
setState(data);
}
}, [loading, data])
So what is the answer? lol
Optionally using refetch (or poll), (?) From Apollo docs,
Refetching enables you to refresh query results in response to a particular user action, as opposed to using a fixed interval.
(Apollo-refeching) (and optionally setting up the caching strategy)
function App () {
const { loading, data, refetch } = useQuery(THE_QUERY);
return (
loading
? <div>..loading</div>
: <ComponentWIthFormAndView refetch={refetch} /> // call refetch after a user action
)
}
I don't store return data from query to react state. I just feel like that's an anti-pattern. You should just use the returned data as it is like below:
const { loading, data, error } = useQuery(SOME_QUERY) // If you absolutely need to cache the mutated data you can do the below. But // most of the time you won't need to use useMemo at all. const cachedMutatedData = useMemo(() => { if (loading || error) return null // mutate data here return data }, [loading, error, data]) if (loading) return <Loader /> if (error) return <Error /> // safe to assume data now exist and you can use data. const mutatedData = (() => { // if you want to mutate the data for some reason return data })() return <YourComponent data={mutatedData} />But if you must store the returned data, could do below:
const { loading, data, error } = useQuery(SOME_QUERY) const [state, setState] = React.useState([]) React.useEffect(() => { // do some checking here to ensure data exist if (data) { // mutate data if you need to setState(data) } }, [data])
If use setState inside the useEffect, isn't it going to re-render the component thus create an infinite loop (because useQuery will be called again)?
I don't store return data from query to react state. I just feel like that's an anti-pattern. You should just use the returned data as it is like below:
const { loading, data, error } = useQuery(SOME_QUERY) // If you absolutely need to cache the mutated data you can do the below. But // most of the time you won't need to use useMemo at all. const cachedMutatedData = useMemo(() => { if (loading || error) return null // mutate data here return data }, [loading, error, data]) if (loading) return <Loader /> if (error) return <Error /> // safe to assume data now exist and you can use data. const mutatedData = (() => { // if you want to mutate the data for some reason return data })() return <YourComponent data={mutatedData} />But if you must store the returned data, could do below:
const { loading, data, error } = useQuery(SOME_QUERY) const [state, setState] = React.useState([]) React.useEffect(() => { // do some checking here to ensure data exist if (data) { // mutate data if you need to setState(data) } }, [data])
Thank you so much, I was about to pluck my eyes out, now I can sleep peacefully. This solved my problem.
Is there any way to use multiple queries before a component render inside the component itself?
I don't store return data from query to react state. I just feel like that's an anti-pattern. You should just use the returned data as it is like below:
If data is a collection, and you're going to mutate that data, I often see people attaching refetch queries on the mutation to pull it all back from the server after adding/removing. This seems like an anti-pattern.
Instead, it is better to use the returned data from the query as state, then add or remove the results of the mutation to it. No refetch.
Is there a reason why my example below fetches 4+ times? In the Network tab, I see it has the data from the very first fetch. The big problem with this is that the resolver then runs like 4+ times, causing unintended logic consequences on the backend.
Using @jinshin1013's example above, it fetches only once, but that feels like it is defeating the purpose of Apollo Client and I don't know if I am losing caching or other benefits (not to mention loading, error, etc.)
import { useQuery } from "@apollo/client";
import { OneExample } from "./query";
export const Example = () => {
const id = "FVox336y";
const { data, loading, error } = useQuery(OneExample, {
fetchPolicy: "cache-first",
variables: {
accessId: id,
},
});
return loading ? "loading" : "data";
};