[英]how do I consume django api from react frontend
I'm new to React
, I've written a Django API
endpoint to perform some kind of sync
.我是React
新手,我写了一个Django API
端点来执行某种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?我希望从React
页面调用这个API
,点击TextLink
- 说立即同步,我应该如何 go 来做呢? 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.根据来自 API(200 或 400/500)的响应,我想显示 Sync failed,成功同步后,我想再次显示 Sync Now,但带有另一个文本 Last Sync Time: DateTime(为此我添加了我的 Django 模型中的一个键),我该如何使用它。
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.另外,我有一个跟进,比如说我们有另一个 state 同步,而不是 Sync Now 和 Synced,它一直存在,直到返回成功或失败,从服务器轮询是一个不错的选择,还是有任何其他方式。 I know of websockets
but not sure which can be used efficiently.我知道websockets
,但不确定哪个可以有效使用。
I've been stuck here from 3 days with no real progress.我已经被困在这里 3 天了,没有真正的进展。 Anything will help.任何事情都会有所帮助。 Thanks in advance.提前致谢。
Have you setup your django app to communicate with your react frontend?您是否设置了 django 应用程序以与您的反应前端进行通信?
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>
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.