Home > Software design >  how do I consume django api from react frontend
how do I consume django api from react frontend

Time:12-20

I'm new to React, I've written a Django API endpoint to perform some kind of sync. I want this API to be called from a React page, on clicking a TextLink - say Sync Now, how I should go about doing it? Based on the response from the API(200 or 400/500), I want to display Sync failed, on successful sync, I want to show Sync Now again, but with another text Last Sync Time: DateTime(for this I've added a key in my Django model), how can I use this as well.

Also, I've a followup, say instead of Sync Now and Synced we have another state Syncing, which is there until a success or failure is returned, Is polling from the server is a good option, or is there any other way. I know of websockets but not sure which can be used efficiently.

I've been stuck here from 3 days with no real progress. Anything will help. Thanks in advance.

CodePudding user response:

I'd do something like that:

// Store last sync date in state with default value null

const [lastSyncDate, setLastSyncDate] = useState(null);
const [isLoading, setIsLoading] = useState(false);

const handleApiCall = async () => {
  try {
    setIsLoading(true);
    const response = await fetch('api.url');

    if (response.status === 200) {
     const currentDate = Date.now().toString();
     setLastSyncDate(currentDate);
    }

  }
  catch(error) {
    // handle error here
  }
  finally {
    setIsLoading(false);
  }
  
}

if (isLoading) {
  return 'Loading...';
}

return (
 <div onClick={() => handleApiCall()}>
   {lastSyncDate !== null ? `lastSynced: ${lastSyncDate}` : "Sync now"}
</div>
)
  • Related