8

currently i am using SWR to data fetching, i trying to use Mutation feature of SWR to refetch the new data but this occurred a problem when i am calling mutate() by key was added new query params.

Here's my code not working:

import useSWR, { useSWRConfig } from 'swr'

function Profile () {
  const { mutate } = useSWRConfig()
  const { data } = useSWR('/api/post', fetcher)

  return (
    <div>

      <h1>Title post {data.title}.</h1>

      <button onClick={() => {            
        mutate('/api/post?author=1&pricing=1')
      }}>
        View more information of this post!
      </button>

    </div>
  )
}

I read docs from SWR and i know the key of the mutate should be the same to key in useSWR() but in my case need more query params to get the corresponding data

How can i solve this problem? Helps me please!

Anna
  • 228
  • 1
  • 3
  • 13

1 Answers1

13

I wouldn't recommend using mutate in this scenario because the key (the URL) you want to use in the mutation is different from the original one. When mutate is called it'll update the cache for '/api/post' which will then contain data from '/api/post?author=1&pricing=1' in it.

As an alternative, I'd suggest you make the key an array in the useSWR call so that multiple arguments can be passed to the fetcher.

const [queryParams, setQueryParams] = useState('')
const { data } = useSWR(['/api/post', queryParams], fetcher)

Then, in your button onClick handler, you can update the queryParams state value to trigger a re-render and initiate a new request with the query parameters.

<button onClick={() => {            
    setQueryParams('?author=1&pricing=1')
}}>
    View more information of this post!
</button>

You also need to modify the fetcher function slightly to expect multiple arguments, and also append the query params you pass to the URL.

const fetcher = (url, queryParams = '') => {
    // Example fetch to demonstrate the logic
    return fetch(`${url}${queryParams}`)
}

With this change you now have different keys (and cached data) for each URL you make a request for.

juliomalves
  • 42,130
  • 20
  • 150
  • 146