I am new in NextJS and using the NextJs with React. So I am fetching the users list using trpc with useQuery.
Then I am filter users lists based on user name. I have added the sample code but I have more logic in that.
In below code when I click the button I am passing the username like "user1", In parent component(Users.tsx) the method updateFilter triggered and getting the value of user.In this method I am trying to set the setUsersData values with object of users. I am getting the error. Can someone help me to fix the issue.
Users.tsx
const Page = () => {
const users = trpc.users.getUsersSummary.useQuery(
{},
{
onError(err) {
console.log('Failed to retrieve users summary')
},
},
);
const [usersData, setUsersData] = useState(users);
const filteredLists = (username: string) => {
return users?.data?.users.filter((user: any) =>{
user.name === username;
});
}
const updateFilter = (username: string) => {
const getFilterQuery = filteredLists(username);
setUsersData(current => {
const data = {...current.data};
data.users = getFilterQuery;
return {...current, data};
});
};
return (
<div>
<UserList setUserType={updateFilter} usersSummary={usersData.data} />
</div>
)
}
Userslists.tsx
// Global
import { useEffect } from 'react';
export const UserList = ({ usersSummary, setUserType }: UserFilterPropTypes) => {
const items = usersSummary?.users
const handleChange = () => {
setUserType("user1")
}
return (
<div>
<button onclick= { handleChange()> Filter < /button>
//Iterating the data
< /div>
)
}
Json getting from response:
[
{
"result": {
"data": {
"json": {
"totalUsers": 40,
"users": [
{
"name": "user1",
"status": "Active"
},
{
"name": "user2",
"status": "De Active"
},
{
"name": "user3",
"status": "Active"
},
{
"name": "user4",
"status": "De Active"
},
{
"name": "user5",
"status": "Active"
},
]
}
}
}
}
]
Error Details:
Argument of type ‘(current: (QueryObserverRefetchErrorResult
2
Answers
Notice the
<button onclick= { handleChange()> Filter < /button>
code. Theonclick
handler has to beonclick={handleChange}
That way the
handleChange
will be triggered when the onclick event happen. The way you have it now, it executes thehandleChange
method at the time you declare the component and that’s not what you want.As i see in your code ,inside your Page component
the following piece of code ,consider usersData as result return by useQuery which is QueryObserverRefetchErrorResult
Now when you click on button updateFilter is called( nahuelhds also mention syntax error please check that),Which make call to filteredLists which returns an array,So you are basically trying to assign an array
to QueryObserverRefetchErrorResult.
To fix this,Instead of assigning QueryObserverRefetchErrorResult to usersData you should first make an array and then store array in state.
You should just save the filterQueryStr as a state instead of store filtered array inside state .
consider the below code.
I Hope this will help.