vercel / swr-site

The official website for SWR.
https://swr.vercel.app
Apache License 2.0
481 stars 351 forks source link

Question for “Mutation & Revalidation” #582

Closed JoseIsama closed 2 months ago

JoseIsama commented 2 months ago

Please i want to update the data in the intial requested swr with the data of the second updated swr request export default

function Home({data}){ const [page, setPage] = useState(1) const [posts, setPosts] = useState([]); const [loading, setLoading] = useState(true); const [persistData, setPersistData ] = useRemember([], 'homeposts'); const [shouldFetch, setShouldFetch] = useState(true);

const {ref, inView} = useInView({ threshold: 0, })

const {cursors, setCursors, updateNextCursors, refresh} = usePaginate();

const [nextCursors, setNextCursors] = useState(cursorData); const getQueryString = () => { let queryString = /home?page=${page}; const cursorString = encodeURIComponent(cursors.post_id);

  queryString += `&cursor=${cursorString}`;

return queryString;

}; const initialQueryString = /home?page=${page}; const {data: homeespo, isLoading: homeloading, isError: homeerror, mutate} = useSWR(initialQueryString, fetcher) const {data: upDates, isLoading: loadingUpdates} = useSWR(cursors?.state ? getQueryString() :null, fetcher);

const dispatch = useDispatch(); useEffect(()=>{ //get the user post dispatch(setStorageKey('homeposts')) }, []) useEffect(()=>{ if (!loadingUpdates ) { console.log(upDates) if (upDates){ if (upDates.data > 0){ mutate([...postdata.data, upDates.data] , false); } } } }, [upDates, loadingUpdates]) console.log(upDates) useEffect(()=>{ //get the user post dispatch(setStorageKey('homeposts')) }, [persistData])

const handleRefresh = () => { setLoading(true); setPage(1); setNextCursors(cursorData); setShouldFetch(true); };

useEffect(() => {

if (!homeloading){ console.log(homeerror) if (homeespo){

  setPosts(homeespo.data);
}else{

}

} // Function to load more posts

}, [/* loading, currentPage, lastPage */ ]);

useEffect(()=>{ if (inView){ updateNextCursors(homeespo.data); console.log('loading')

}

}, [inView])

return (
  <div className="w-full min-h-screen">
  <HelmetProvider>
    <Helmet>
      <title>Home</title>
    </Helmet>
  </HelmetProvider>
  {homeloading ? (
    <Loader className={`center-relative`} />
  ) : (
    <>
      {empty(homeespo) ? (
        <div>
          <span>
            No espos available. You can create one{' '}
            <span
              className="hover:link  text-blue-500"
              onClick={(e) => {
                e.stopPropagation();
                router.navigate('/Espo');
              }}
            >
              here
            </span>
          </span>
        </div>
      ) : (
        <Postmarkupforsessionuser data={homeespo.data} />

      )}

        <div className='m-0 p-0' ref={ref} />

    </>
  )}
</div>
  );

};