0

I'm stuck with Vercel's SWR mutate system. I'm going to try to explain my situation, I hope I can make it.

I'm working on a social media app, it's something like a combination of Instagram and Twitter. We have a weird RestAPI design in here. for example, we have three endpoints, and let's say A, B, C. all of them return the same type object array(post[]) and have three routes for these endpoints.

// Post.jsx
const Post =(props)=> {
 const deleteHandler =()=> {
   //delete post

   // update cached SWR data with mutate func
 }
  return(
    <div>
      // some other UI components
      </div>
  )
}
// pageX.jsx
const PageX =()=> {
  const {data:posts} =useSWR("/api/A", fetcher);

  return(
    <List dataSource={posts} render={p=>(<Post data={p}/>)}/>
  )
}

// pageY.jsx
const PageY =()=> {
  const {data:posts} =useSWR(["/api/B",crateDate],fetcher);

  return(
    <List dataSource={posts} render={p=>(<Post data={p}/>)}/>
  )
}

// pageZ.jsx
const PageZ =()=> {
  const {data:posts} =useSWR(["/api/C",categoryId], fetcher);

  return(
    <List dataSource={posts} render={p=>(<Post data={p}/>)}/>
  )
}

as you can see, I need to update cached data but I don't know how can I pass the correct SWR key to mutate function in that delete handler. In the end, I have many keys because of API design. Also, I use useSWRInfinite too, and it generates new keys when scrolling down.

And we are using NextJS React Framework.

Ronak Shah
  • 377,200
  • 20
  • 156
  • 213
mafirat
  • 258
  • 1
  • 8
  • 1
    You could pass the key (or even the delete handler altogether) through props or React Context down to `Post`. – juliomalves Apr 24 '21 at 16:16
  • passing through props is what I'm doing now actually. But in the post component, there are so many subcomponents that need to access the delete handler or mutate function. But using a GlobalMutateContext may a good solution, I will try. Thank you. – mafirat Apr 25 '21 at 17:30

0 Answers0