Reputation: 209
After creating useState Hook For gender, age useState('30'); useState('female'); If you set
http://api.minsu.com/product/${id}?gender=feamle&age=30
I am using react-query(useQuery) for api state management library. It's no different, I'm creating a dynamic page right now and then showing the page based on the id value.
This is an example.
https://api.minsu.com/product/${id}
And on the detailed page, http://api.minsu.com/product/${id}?gender=feamle&age=30
In this way, random data is entered for gender and age, and only specific data of a 30-year-old woman is shown.
select box (option)
After choosing female and age as
Set the api to https://api.minsu.com/product/${id}?gender=${gender}&age=${age}
I want to show the detail page after receiving gender and age through api get according to the selected select by modifying it in this way.
It seems that I am not directly using input and select box, and I do not know how to write query using useState Hook.
But I don't know what to do.
This is my code now.
I thought about it for about an hour. I have created age and gender with setState('').
const [gender, setGenders] = useState('female');
const [age, setAges] = useState('30');
const fetchDetail = async () => {
const res = await
fetch(`https://api.minsu.com/product/${id}?gender=${female}&age=${age}`, {
headers: {
Authorization: `Bearer ${token}`,
},
withCredentials: true
});
return res.json();
}
const { data: ProductDetail, status, error, isFetching } = useQuery('productDetail', fetchDetail, {
notifyOnChangeProps: ['data'],
staleTime: 100000000,
})
console.log(ProductDetail);
return (
<input type="number" placeholder={Enter your age} .... />
<button onClick={onClick} />
<option>Select gender</option>
<option value="male">Male</option>
<option value="female">Female</option>
)
That is, to summarize
const [inputs, setInputs] = useState({
age: '30',
gender: 'female',
})
const {age, gender} = inputs;
const onChange = (e) =>{
setInputs({ ...inputs, [e.target.age]:e.target.value })
}
return (
<input name="age" onChange={onChange} placeholder = "age"/>
<input name="gender" onChange={onChange} placeholder = "gender"/>
)
I want to change the query by executing onChange after creating the input, but the rendering is not working.
Upvotes: 2
Views: 948
Reputation: 63
you can use this (check my comments inside snippet):
import { useQueryClient } from "@tanstack/react-query";
const [id, setId] = useState("someId") // you don't say what should we do with id?!
const [age, setAge] = useState("30")
const [gender, setGender] = useState("female")
const onAgeChange = (e) => {
setAge(e.target.value) // you used: e.target."""age"""!
}
const onGenderChange = (e) => {
setGender(e.target.value) // you used: e.target."""age"""!
}
const {
data: ProductDetail,
status,
error,
isFetching,
} = useQuery(
['productDetail', id, age, gender],
fetchDetail,
{
notifyOnChangeProps: ['data'],
staleTime: 100000000,
},
);
const queryClient = useQueryClient();
useEffect(() => {
queryClient.invalidateQueries(['productDetail', id, age, gender]); // this will update your data automatically if id, age and/or gender change
}, [id, age, gender])
return (
<>
<input name="age" onChange={onAgeChange} value={inputs.age} placeholder="age" /> {/* you missed the """value={}""" */}
<input name="gender" onChange={onGenderChange} value={inputs.gender} placeholder="gender" /> {/* you missed the """value={}""" */}
</>
)
Upvotes: 0
Reputation: 203302
Assuming you're updating the local state (age
and gender
) correctly and just need to trigger the query again.
To subscribe to a query in your components or custom hooks, call the useQuery hook with at least:
- A unique key for the query
- A function that returns a promise that:
- Resolves the data, or
- Throws an error
The unique key you provide is used internally for refetching, caching, and sharing your queries throughout your application.
If your query function depends on a variable, include it in the query key.
Given the request URL:
`https://api.minsu.com/product/${id}?gender=${gender}&age=${age}`
Then id
, age
, and gender
should all probably be included as part of the query key.
const {
data: ProductDetail,
status,
error,
isFetching,
} = useQuery(
['productDetail', id, age, gender],
fetchDetail,
{
notifyOnChangeProps: ['data'],
staleTime: 100000000,
},
);
Upvotes: 0