gpt4 book ai didi

How to delay or wait fetch before load mockServiceWorker.js on page reloading(如何在页面重新加载时延迟或等待在加载moockServiceWorker.js之前获取)

转载 作者:bug小助手 更新时间:2023-10-24 20:49:47 25 4
gpt4 key购买 nike



I am currently developing a front-end application in Nextjs, using RTK Query for API fetching and use MSW for its mock.

我目前正在Nextjs中开发一个前端应用程序,使用RTK Query进行API获取,并使用MSW进行模拟。


If mockServiceWorker.js is already loaded at the time the page is loaded, the API mock will be intercepted without problems. However, when the page is reloaded from the browser, the API query is executed first and the API is called before msw catches it, resulting in a 500 error.

如果在加载页面时已经加载了mock ServiceWorker.js,则mock API将被毫无问题地拦截。但是,当从浏览器重新加载页面时,首先执行API查询,然后在MSW捕获它之前调用API,从而导致500错误。


enter image description here

在此处输入图像描述


I struggle with controlling when RTK query is called and I have also looked into when public files like mockServiceWorker.js are loaded, etc., but have not reached to find a solution.

我很难控制什么时候调用RTK查询,我还研究了什么时候加载像mock ServiceWorker.js这样的公共文件,等等,但还没有找到解决方案。


Here is the sample page code:
src/pages/_app.tsx

以下是示例页面代码:src/ages/_app.tsx


import React, { useEffect } from 'react';

import { CacheProvider, EmotionCache } from '@emotion/react';
import { AppProps } from 'next/app';
import Head from 'next/head';

import { GlobalLayout } from '../components/globals/GlobalLayout';
import { Providers } from '../components/globals/Providers';
import createEmotionCache from '../createEmotionCache';
import '../styles/globals.css';

if (process.env.NODE_ENV !== 'production') {
if (process.env.NEXT_PUBLIC_ENABLE_MOCK_SERVER) {
const { worker } = require('./mocks/browser')
worker.start()
}
}

// Client-side cache, shared for the whole session of the user in the browser.
const clientSideEmotionCache = createEmotionCache();

export interface MyAppProps extends AppProps {
emotionCache?: EmotionCache;
}

export default function MyApp(props: MyAppProps) {
const { Component, emotionCache = clientSideEmotionCache, pageProps } = props;

useEffect(() => {
// Remove the server-side injected CSS.
const jssStyles = document.querySelector('#jss-server-side');
if (jssStyles) {
jssStyles.parentElement?.removeChild(jssStyles);
}
}, []);

return (
<CacheProvider value={emotionCache}>
<Head>
<title>Front Template</title>
<meta name="viewport" content="initial-scale=1, width=device-width" />
<meta name="description" content="Front Template" />
</Head>
<Providers>
<GlobalLayout>
<Component {...pageProps} />
</GlobalLayout>
</Providers>
</CacheProvider>
);
}

src/pages/test.tsx

Src/ages/est.tsx


export default function Test() {
const [fetch, { data }] = usePostApiFooMutation();
useEffect(() => {
fetch(args);
}, [fetch, args]);
return (
<>
<Button onClick={() => fetch(args)}>fetch</Button>
<div>{JSON.stringify(data?.payload)}</div>
</>
);
}

environment:

环境:



  • typescript:4.5.2

  • react:18.2.0

  • next:13.4.3

  • reduxjs/toolkit:1.9.5

  • msw:1.2.1


更多回答
优秀答案推荐

I believe this issue happens because registering (and activating) a Service Worker is an asynchronous action. This creates a race condition between your app rendering and making the initial request, and MSW activating.

我认为发生这个问题是因为注册(和激活)服务工作者是一个异步操作。这会在您的应用程序呈现和发出初始请求,以及MSW激活之间产生竞争条件。


To tackle this, defer your application's mounting until the worker is ready to process requests. We mention an example of how to do this in the Deferred mounting recipe in the documentation. Hope this helps.

要解决此问题,请将应用程序的挂载推迟到工作进程准备好处理请求为止。我们在文档中的延迟安装配方中提到了一个如何做到这一点的示例。希望这能帮上忙。



The following link has an answer to a similar problem.
MSW(Mock Service Worker) in Next js first render not working

下面的链接提供了类似问题的答案。下一个JS中的MSW(模拟服务工作者)首先呈现不起作用


I added the same code to monitor the worker startup before mounting the application and it works fine.

在挂载应用程序之前,我添加了相同的代码来监视Worker启动,并且运行良好。


更多回答

Well, it was already documented in the official documentation. It is simpler and smarter than creating an ostentatious provider! TYVM

嗯,官方文件里已经有记载了。这比创建一个炫耀的供应商更简单、更聪明!轮胎

Your answer could be improved with additional supporting information. Please edit to add further details, such as citations or documentation, so that others can confirm that your answer is correct. You can find more information on how to write good answers in the help center.

您的答案可以通过其他支持信息来改进。请编辑以添加更多详细信息,如引用或文档,以便其他人可以确认您的答案是正确的。你可以在帮助中心找到更多关于如何写出好答案的信息。

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com