1. How does it work?
You can implement
swr like this: src/app/context/ConatactContext/index.tsx
import useSWR from 'swr';
import { uniqueId } from 'lodash';
import { sub } from 'date-fns';
import { getFetcher} from '@/app/api/globalFetcher';
const {data:contactsData,isLoading:isContactsLoading,error:contactsError,mutate} = useSWR('/api/contacts',getFetcher);
useEffect(() => {
if(contactsData){
const allContacts = contactsData.data;
setContacts(allContacts);
if(contacts.length===0){
const initialStarredContacts = allContacts.filter((contact: { starred: any; }) => contact.starred).map((contact: { id: any; }) => contact.id);
setStarredContacts(initialStarredContacts);
setSelectedContact(allContacts[0]);
}
}else if(contactsError){
setLoading(isContactsLoading);
setError(contactsError);
}else{
setLoading(isContactsLoading);
}
}, [contactsData,contactsError]);
{Object.keys(data).map((key, index) => {
return (
<React.Fragment key={index}>
...
...
</React.Fragment>
);
...
...
})
};