npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

@vigilio/react-fetching

v2.0.1

Published

this is a library to consume fetch in react

Downloads

8

Readme

@Vigilio/React-fetching

A simple React Hooks library for data fetching.

Getting Started

useQuery: to consume data fetching GET

    function getUsers = async(url:string) => {
        const response = await fetch("http://yourhost/api" + url);
        const result:Datatype = await response.json();
        return result;
    }


    const { isLoading, data, isSuccess,isError,...rest} = useQuery("/users", getUsers);

    let component = null

    if(isLoading){
        component = <Spinner/>
    }
    if(isSuccess){
        component = <div>{JSON.stringify(data)}</div>
    }
    if(isError){
        component = <div>Oppss error!</div>
    }
    <div>
        {component}
    </div>;
  • Api reference
const options = {};

const showUser = useQuery("/users", getUsers, options);

const options = {
    skipFetching: false, // skip fetch ->default false
    placeholderData: null, //placeholder  ->default null
    transformData: null, //transform success data ->default null
    staleTime: null, // if you want refetch for a seconds 1 = 1000 ms
    refetchIntervalInBackground: false, // when the client change the page, it will refetch
    onError: null, // callback when the fetch is not success (err)=>{} //default null
    onSuccess: null, // callback when the fetch is  success (data)=>{} //default null
    refetchOnReconnect: false, // when the net back it fetching // default false
    delay: null, // delay to consume fetch //default null
    clean: true, // it no clean when refetch data //default clean
};

useMutation: to consume data fetching POST-PUT-DELETE-PATCH

interface Body {
    name: string;
}

async function addUser(url: string, body: Body) {
    const data = await fetch(url, {
        method: "POST",
        body: JSON.stringify(body),
        headers: {
            "Content-Type": "application/json",
        },
    });
    return data;
}

const { mutate, isLoading, isSuccess, ...rest } = useMutation(
    "/users",
    addUser
);
const [name, setName] = useState("");

// mutate
function handleSubmit(e: JSXInternal.TargetedEvent) {
    e.preventDefault();

    //mutate(body,options) :
    mutate(
        { nombre },
        {
            onSuccess: (data) => {
                console.log(data);
                // you can pass for props  showUser to update users GET
                //  when add a user for example
                showUser.refetching();
            },
            onError: (error) => {
                console.log(error);
            },
        }
    );
}

<form onSubmit={handleSubmit}>
    <div className="">
        <label htmlFor="">name</label>
        <input
            type="text"
            value={nombre}
            placeholder="name"
            onChange={(e) => setName(e.currentTarget.value)}
        />
    </div>
    <button type="submit">{isLoading ? "loading" : "send"}</button>
</form>;

You can use Mutate async if you prefer

const { mutateAsync, isLoading, isSuccess, ...rest } = useMutation(
    "/users",
    addUser
);
// mutateAsync
async function handleSubmit(e: JSXInternal.TargetedEvent) {
    e.preventDefault();
    try {
        const data = await mutateAsync({ nombre });
        //
    } catch (err) {
        // your error response
    }
}
  • Api reference
// mutate options
{
    onSuccess?: (data) => {};
    onError?: (error) => {};
    transformData?: (data) => Data; // you cand modify response data
}

USING AXIOS

const baseurl = axios.create({ baseURL: "http://yourhost/api" });

interface Api {
    id: number;
    name: string;
}

async function showUsers(url: string) {
    const { data } = await baseurl.get<Api[]>(url);
    return data;
}

const { isLoading, data, ...rest } = useQuery("/users", showUsers);

//....

MORE EXAMPLES

Dinamic Params

interface UserTypeApi {
    id: number;
    nombre: string;
}
async function showById(url: string) {
    const { data } = await baseurl.get<UserTypeApi>(url);
    return data;
}
export function UserPageById() {
    const { id } = useParams() as { id: string };

    const { isLoading, data, isSuccess, isError, error } = useQuery(
        `/users/${id}`,
        showById
    );
    let component = null;
    if (isLoading) {
        component = <h2>Cargandoo...</h2>;
    }
    if (isSuccess) {
        component = <p>{JSON.stringify(data)}</p>;
    }
    if (isError) {
        component = <p>{JSON.stringify(error)}</p>;
    }
    return <div>{component}</div>;
}