Skip to content

misantronic/react-wrap-request

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

react-wrap-request

A react-hook implementation for the wrap-request.

basic usage

function Component() {
    const { $: items } = useWrapRequest(() => fetch(`https://.../`), {
        defaultData: [],
        deps: [], // fetch will happen when component did mount
    });

    return <div>{items.map((item) => item.id)}</div>;
}

working with deps

function Component(props) {
    const { $: items } = useWrapRequest((id) => fetch(`https://.../${id}`), {
        defaultData: [],
        deps: [props.id], // whenever props.id update, wrapRequest will re-fetch
    });

    return <div>{items.map((item) => item.id)}</div>;
}

manual request

function Component(props) {
    const wrapRequest = useWrapRequest((id) => fetch(`https://.../${id}`), {
        defaultData: [],
    });

    useEffect(() => {
        wrapRequest.request([100]);
    }, []);

    return <div>{wrapRequest.items.map((item) => item.id)}</div>;
}

transform request

see https://github.com/misantronic/wrap-request#pipe

function Component() {
    const items = useWrapRequest(() => fetch(`https://.../`), {
        defaultData: [],
        deps: [],
    }).pipe((items) => items.map((item) => ({ id: item.id })));

    console.log('source', items.source);
    console.log('transformed result', items.$);

    return <div>{items.$.map((item) => item.id)}</div>;
}

pattern matching

function Component(props) {
    const wrapRequest = useWrapRequest((id) => fetch(`https://.../${id}`), {
        defaultData: [],
        deps: [props.id],
    });

    return wrapRequest.match({
        loading: () => <div>Loading</div>,
        error: () => <div>Error</div>,
        empty: () => <div>No items.</div>,
        fetched: (items) => <div>{items.map((item) => item.id)}</div>,
    });
}

Releases

No releases published

Packages

No packages published

Contributors 3

  •  
  •  
  •