T
TanStack3y ago
other-emerald

Get fetched data in another component

I have this hook:
import { useQuery } from '@tanstack/react-query'
import axios from 'axios'

const GITHUB_URL = import.meta.env.VITE_GITHUB_URL
const GITHUB_TOKEN = import.meta.env.VITE_GITHUB_TOKEN

export const useSearchUsers = (query) => {
return useQuery({
queryKey: ['users', { query }],
queryFn: async () => {
const response = await axios.get(
`${GITHUB_URL}/search/users?q=${query}`,
{
headers: {
Authorization: `token ${GITHUB_TOKEN}`
}
}
)
return response.data
},
enabled: !!query
})
}
import { useQuery } from '@tanstack/react-query'
import axios from 'axios'

const GITHUB_URL = import.meta.env.VITE_GITHUB_URL
const GITHUB_TOKEN = import.meta.env.VITE_GITHUB_TOKEN

export const useSearchUsers = (query) => {
return useQuery({
queryKey: ['users', { query }],
queryFn: async () => {
const response = await axios.get(
`${GITHUB_URL}/search/users?q=${query}`,
{
headers: {
Authorization: `token ${GITHUB_TOKEN}`
}
}
)
return response.data
},
enabled: !!query
})
}
Here i set the query:
import { useState } from 'react'
import { useSearchUsers } from '../../hooks/useGithubUsers'

const UserSearch = () => {
const [text, setText] = useState('')
const [query, setQuery] = useState('')

const { data } = useSearchUsers(query)

const handleChange = (e) => setText(e.target.value)

const handleSubmit = (e) => {
e.preventDefault()

if (text === '') {
alert('Please enter something')
} else {
setQuery(text)
setText('')
}
}

return (
<div className='grid grid-cols-1 xl:grid-cols-2 lg:grid-cols-2 md:grid-cols-2 mb-8 gap-8'>
<div>
<form onSubmit={handleSubmit}>
<div className='form-control'>
<div className='relative'>
<input
type='text'
className='w-full pr-40 bg-gray-200 input input-lg text-black'
placeholder='Search'
value={text}
onChange={handleChange}
/>
<button
type='submit'
className='absolute top-0 right-0 rounded-l-none w-36 btn btn-lg'
>
Go
</button>
</div>
</div>
</form>
</div>
{data?.items.length > 0 && (
<div>
<button className='btn btn-ghost btn-lg'>Clear</button>
</div>
)}
</div>
)
}

export default UserSearch
import { useState } from 'react'
import { useSearchUsers } from '../../hooks/useGithubUsers'

const UserSearch = () => {
const [text, setText] = useState('')
const [query, setQuery] = useState('')

const { data } = useSearchUsers(query)

const handleChange = (e) => setText(e.target.value)

const handleSubmit = (e) => {
e.preventDefault()

if (text === '') {
alert('Please enter something')
} else {
setQuery(text)
setText('')
}
}

return (
<div className='grid grid-cols-1 xl:grid-cols-2 lg:grid-cols-2 md:grid-cols-2 mb-8 gap-8'>
<div>
<form onSubmit={handleSubmit}>
<div className='form-control'>
<div className='relative'>
<input
type='text'
className='w-full pr-40 bg-gray-200 input input-lg text-black'
placeholder='Search'
value={text}
onChange={handleChange}
/>
<button
type='submit'
className='absolute top-0 right-0 rounded-l-none w-36 btn btn-lg'
>
Go
</button>
</div>
</div>
</form>
</div>
{data?.items.length > 0 && (
<div>
<button className='btn btn-ghost btn-lg'>Clear</button>
</div>
)}
</div>
)
}

export default UserSearch
And here i want to use the data and also update it when a new search is done:
import UserItem from './UserItem'
import Spinner from '../layout/Spinner'

import { useSearchUsers } from '../../hooks/useGithubUsers'
const UserResults = () => {
const { data, isPending } = useSearchUsers()

return (
<div className='grid grid-cols-1 gap-8 xl:grid-cols-4 lg:grid-cols-3 md:grid-cols-2'>
{!isPending ? (
data?.items.map((user) => <UserItem key={user.id} user={user} />)
) : (
<Spinner />
)}
</div>
)
}

export default UserResults
import UserItem from './UserItem'
import Spinner from '../layout/Spinner'

import { useSearchUsers } from '../../hooks/useGithubUsers'
const UserResults = () => {
const { data, isPending } = useSearchUsers()

return (
<div className='grid grid-cols-1 gap-8 xl:grid-cols-4 lg:grid-cols-3 md:grid-cols-2'>
{!isPending ? (
data?.items.map((user) => <UserItem key={user.id} user={user} />)
) : (
<Spinner />
)}
</div>
)
}

export default UserResults
6 Replies
stormy-gold
stormy-gold3y ago
What is your question? Ah, got it. To access the cache entry you need to know the key, in your case [’users’,{query}]. So in UserResults you also need to pass query into your hook. Maybe prop drilling or a global state might be suitable for you
other-emerald
other-emeraldOP3y ago
Ah ok i tought i would dont need to add the query in the userResults, i tought i could get the data with only the key, the problem is i cant send props cause the components is not connected, maybe i could add a context to my hook and set it equal to the data? So i should call it in my UserResults something like?
const { data, isPending } = useSearchUsers(['users',query])
const { data, isPending } = useSearchUsers(['users',query])
stormy-gold
stormy-gold3y ago
No, just query, like in the other component.
other-emerald
other-emeraldOP3y ago
Ok but when to use the key?
stormy-gold
stormy-gold3y ago
Your problem is very basic. Did you read the documentation?
foreign-sapphire
foreign-sapphire3y ago
use set enabled: !!query it mean when query is falsely value it will fetch data unless enabled true so query key also change when query change it treat key as deps useEffect please read documents more

Did you find this page helpful?