skip to Main Content

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


  1. Notice the <button onclick= { handleChange()> Filter < /button> code. The onclick handler has to be onclick={handleChange}

    That way the handleChange will be triggered when the onclick event happen. The way you have it now, it executes the handleChange method at the time you declare the component and that’s not what you want.

    Login or Signup to reply.
  2. 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

    const users = trpc.users.getUsersSummary.useQuery(
    {},
    {
        onError(err) {
            console.log('Failed to retrieve users summary')
        },
    });
    const [usersData, setUsersData] = useState(users);`
    

    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.

    const Page = () => {    
    const users = trpc.users.getUsersSummary.useQuery(
        {},
        {
            onError(err) {
                console.log('Failed to retrieve users summary')
            },
        },
    );
    const [usersData, setUsersData] = useState([]);
    const [filterQuery,setFilterQuery]=useState('')
    
    //when query response change
    useEffect(()=>{
        //you can use shorthand syntax like users?.data?.users
        if(users && users.data && Array.isArray(users.data.users)){
            setUsersData(users.data.users)
        }
    },[users])
    
    const filteredLists = useMemo((username: string) => {       
        if(filterQuery==='')return  usersData
        return usersData.filter((user: any) =>{
            //you can also try user.name.includes(filterQuery) for short keywords
            return user.name === filterQuery;
        });
    },[filterQuery,usersData])
    
    //updateFilter will only update filterQuery string, you can directly pass setFilterQuery to child component
    const updateFilter = useCallBack((username: string) => {
        setFilterQuery(username)
    });
    
    return (
        <div>
            <UserList setUserType={updateFilter} usersSummary={filteredLists}     />
        </div>
    )
      }
    

    I Hope this will help.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search