Skip to content

OmerTal/react-hook-use-async

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

7 Commits
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

React UseAsync Hook

A Custom React hook for any asynchronous usages, including interacting with server side in the most efficient way.

Example usage

   import { useAsync } from "@omer-tal/react-hook-use-async";
   import axios from 'axios';

   const getUsersFromServer = async (): Promise<user[]> => {
     return await axios
      .get(`myServerPath`)
      .then((res) => res.data)
      .catch((reason) => {
         console.error(reason);
        throw reason;
     });
   };

   const ExampleComponent = () => {
     const [usersFromServer, setUsersFromServer] = useState<user[]>([]);

     useAsync(getUsersFromServer, setUsersFromServer, [], () => {
         console.error("couldn't get users from server");
     });

     return (
       <>
         {!usersFromServer || usersFromServer.length === 0 ? (
              <div>Loading...</div>
         ) : (
              <div>
                  Total users: {usersFromServer.length}
                  {usersFromServer.map((curUser) => (
                      <UserComponent user={curUser} />
                  ))}
              </div>
         )}
       </>
      );
     };

About

A Custom React hook for any asynchronous usages, including interacting with server side in the most efficient way

Topics

Resources

License

Stars

Watchers

Forks

Packages

No packages published