swr icon indicating copy to clipboard operation
swr copied to clipboard

Use SWR in "pure js"

Open hems opened this issue 3 years ago • 2 comments

Bug report

This is more of a "serious" Feature Request than a bug report.

The idea here is that my application isn't 100% written in React.

Some of the logic is written in pure js and if/when needed the javascript part of the application will populate a "Store" ( written using zustand ) so the React components can react accordingly.

Unfortunately SWR doesn't seem to work unless you use the "useSWR" hook which is a shame, SWR provides a lot of good features that "pure js" or "hybrid" ( pure js + react ) applications would benefit from.

There is a discussion here about it as well: https://github.com/vercel/swr/discussions/801

Description / Observed Behavior

Not being able to benefit from all SWR features from a pure js perspective

Expected Behavior

Something similar to zustand as in: works as a hook but also works as pure js

Additional Context

Thank you very much for your hard work, this library is amazing and very very helpful.

hems avatar Sep 01 '21 02:09 hems

This can be one of our long-term goals, but it definitely needs a lot of implementation discussions.

shuding avatar Sep 01 '21 16:09 shuding

This can be one of our long-term goals, but it definitely needs a lot of implementation discussions.

I believe the implementation would be pretty much the same the only difference is that it would emit an event when the values are changed instead of re-triggering render like it does inside of a component?

i.e.

import useSWR from 'swr'

function Profile() {
  const instance = useSWR('/api/user', fetcher)
  instance.on('update', ( { data, error } ) => {
    // update my zustand or whatever state i have to update
  })
}

or another option would be to send an onUpdate function as part of the configuration?

hems avatar Jan 05 '22 16:01 hems