tobyzerner/json-api-models

Using SWR with axios

pepijndik opened this issue · 1 comments

I am wondering, if can i use this package with swr and Axios. I am asking because i saw that it's using some kind of custom store method, and SWR is using stale while revalidate a HTTP cache invalidation strategy. And i very like this stategy?

Saw that it's possible to use any kind of fetcher, but can't think of how i could also use SWR.

Hmm yeah this library isn't really optimised for use in React. I think you'd need to abstract the model store behind a hook that causes consumer components to re-render whenever new data is synced to the store. Something like this (untested):

import { Store } from 'json-api-models';
import useSWR from 'swr';

const models = new Store();

function useModels() {
    const [, setState] = useState(0);

    const sync = useCallback((document) => {
        setState((state) => state + 1);
        return models.sync(document);
    }, []);

    return { models, sync };
}

function useApiRequest(key) {
    const { models, sync } = useModels();

    return useSWR(key, (url) =>
        fetch(url, options)
            .then((response) => response.json())
            .then((document) => sync(document))
    );
}
 
function Profile() {
    const { data: user, error, isLoading } = useApiRequest('/api/users/1');
 
    if (error) return <div>failed to load</div>;
    if (isLoading) return <div>loading...</div>;
    return <div>hello {user.name}!</div>;
}

function SomeOtherComponent() {
    const { models } = useModels();
    const user = models.find('users', '1');

    return <div>{user.name}</div>;
}

Let me know if this works and I might consider adding an example to the docs.