(React-query)Correct refetch after requesting post

Viewed 17

React Component order enter image description here

Homepage components use react-query to get the data The child component UserForm POSTs data. At this time, I have to do a refetch for server data request after POST request, is there a better way than to hand it over to refetch by props?

export default function HomePage() {
  const {
    isLoading,
    isFetching,
    isError,
    refetch,
    data: users,
  } = useQuery(['users'], getUsers);

  if (isLoading) {
    return <h1>loading..!!!</h1>;
  }

  if (isError) {
    return <h1>error</h1>;
  }

  return (
    <div>
      <UserForm refetch={refetch} />
      <ul>
        {users.length ? (
          users?.map((user: IUser) => <UserItem key={user.id} user={user}  refetch={refetch}/>)
        ) : (
          <li>data error</li>
        )}
      </ul>
    </div>
  );
}

UserForm component(post function)

 const handleSubmitAddUser = async (e: FormEvent<HTMLFormElement>) => {
    e.preventDefault();
    if (name) {
      addUser(name)
        .then(() => {
          setName('');
          refetch();
        })
        .catch((err) => console.error(err));
    }
  };
1 Answers

Yes there is. In general, you should avoid using refetch and instead use invalidateQueries():

const queryClient = useQueryClient();
//...
.then(() => {
  // ..
  queryClient.invalidateQueries(["users"]);
});

This will tell React-query that the old users data is stale, and needs to be refetched.

Related