admin管理员组

文章数量:1133961

I was trying React Query and got this at the start of my React app.

import React from 'react'
import { useQuery } from "react-query";
    
const fetchPanets = async () => {
    const result = await fetch('/api/people')
    return result.json()
    }
    
const Planets = () => {
    const { data, status } = useQuery('Planets', fetchPanets)
    console.log("data", data, "status", status)
    return (
        <div>
            <h2>Planets</h2>
        </div>
    )
}
    
export default Planets

I was trying React Query and got this at the start of my React app.

import React from 'react'
import { useQuery } from "react-query";
    
const fetchPanets = async () => {
    const result = await fetch('https://swapi.dev/api/people')
    return result.json()
    }
    
const Planets = () => {
    const { data, status } = useQuery('Planets', fetchPanets)
    console.log("data", data, "status", status)
    return (
        <div>
            <h2>Planets</h2>
        </div>
    )
}
    
export default Planets
Share Improve this question edited May 12, 2023 at 12:14 double-beep 5,49419 gold badges40 silver badges48 bronze badges asked Jan 6, 2021 at 4:25 JamalJamal 1,3212 gold badges11 silver badges16 bronze badges 2
  • 2 in 2022, this problem resurface once again but I dont know what is the correct version to make the problem go away :( – Phạm Huy Phát Commented Sep 30, 2022 at 7:18
  • 1 Make sure you're installing with npm i @tanstack/react-query for v4+. – aderchox Commented Feb 26, 2023 at 9:51
Add a comment  | 

20 Answers 20

Reset to default 103

As the error suggests, you need to wrap your application in a QueryClientProvider. This is on the first page of the docs:

import { QueryClient, QueryClientProvider, useQuery } from 'react-query'

const queryClient = new QueryClient()

export default function App() {
   return (
     <QueryClientProvider client={queryClient}>
       <Example />
     </QueryClientProvider>
   )
}

In my case I was importtng from 'react-query' in one place and '@tanstack/react-query' in another.

While this is most commonly caused by not having your application wrapped in a <QueryClientProvider>, in my case it happened because I was importing some shared components, which ended up with a different context. You can fix this by setting the contextSharing option to true

That would look like:

 import { QueryClient, QueryClientProvider } from 'react-query'
 
 const queryClient = new QueryClient()
 
 function App() {
   return <QueryClientProvider client={queryClient} contextSharing={true}>...</QueryClientProvider>
 }

From the docs: (https://react-query.tanstack.com/reference/QueryClientProvider)

contextSharing: boolean (defaults to false)

Set this to true to enable context sharing, which will share the first and at least one instance of the context across the window to ensure that if React Query is used across different bundles or microfrontends they will all use the same instance of context, regardless of module scoping.

Just make changes like below it will work fine

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import { QueryClient, QueryClientProvider } from "react-query";
const queryClient = new QueryClient();

ReactDOM.render(
  <QueryClientProvider client={queryClient}>
    <App />
  </QueryClientProvider>,
  document.getElementById('root')
);

I got that error when trying to add the react-query devtools.

The problem was I was installing it wrongly according my version, I was using react-query v3.

WRONG FOR react-query V3 (GOOD FOR V4)

import { ReactQueryDevtools } from '@tanstack/react-query-devtools';

OK FOR react-query V3

import { ReactQueryDevtools } from 'react-query/devtools';
import {  QueryClient, QueryClientProvider, useQuery } from 'react-query';
const queryClient = new QueryClient();
const fetchPanets = async () => {
    const result = await fetch('https://swapi.dev/api/people')
    return result.json()
}

const Planets = () => {
    const { data, status } = useQuery('Planets', fetchPanets)
    console.log("data", data, "status", status)
    return (
        <div>
            <h2>Planets</h2>
        </div>
    );
}


export default function Wraped(){
return(<QueryClientProvider client={queryClient}>
        <Planets/>
    </QueryClientProvider>
);
    
}

Single SPA (micro-frontend) - React Query v3.34.15

I was getting this error while trying to integrate a sigle-spa react parcel into the root application.

I used craco-plugin-single-spa-application for the building of a CRA app as a way to adapt it for a parcel. In the entry config I was pointing to my single-spa-react config.

// craco.config.js

const singleSpaApplicationPlugin = require('craco-plugin-single-spa-application')

module.exports = {
  plugins: [
    {
      plugin: singleSpaApplicationPlugin,
      options: {
        orgName: 'uh-platform',
        projectName: 'hosting',
        entry: 'src/config/single-spa-index.cf.js',
        orgPackagesAsExternal: false,
        reactPackagesAsExternal: true,
        externals: [],
        minimize: false 
      }
    }
  ]
}

In the single-spa-index.cf.js file I had the following configs.

import React from 'react'
import ReactDOM from 'react-dom'

import singleSpaReact from 'single-spa-react'

import App from '../App'

const lifecycles = singleSpaReact({
  React,
  ReactDOM,
  rootComponent: App,
  errorBoundary() {
    return <div>Ocorreu um erro desconhecido!</div>
  }
})

export const { bootstrap, mount, unmount } = lifecycles

After reading a bunch of forums and the react-query documentation, the only thing that I figured out I needed to change was pass in the QueryClientProvider the prop contextSharing as true. After had did this change, ran the building and access the route that opens my parcel. I got the same error.

import React from 'react'
import ReactDOM from 'react-dom'
import { QueryClient, QueryClientProvider } from 'react-query'
import { ReactQueryDevtools } from 'react-query/devtools'

import App from './App'

const queryClient = new QueryClient()

const isDevelopmentEnv = process.env.NODE_ENV === 'development'

if (isDevelopmentEnv) {
  import('./config/msw/worker').then(({ worker }) => worker.start())
}

ReactDOM.render(
  <React.StrictMode>
    <QueryClientProvider contextSharing={true} client={queryClient}>
      <App />
      {isDevelopmentEnv && <ReactQueryDevtools initialIsOpen={false} />}
    </QueryClientProvider>
  </React.StrictMode>,
  document.getElementById('root')
)

But, how do I solved that. Well, it was was simple. I couldn't even imagine why it was working locally. But not after building and integration.

The problem was because I put the React Query Provider inside the index o the application and in my single-spa-index.cf.js I was importing import App from '../App' which really wasn't wrapped by the provider. Once I also was importing App in the application index, where It was wrapped making It works locally.

本文标签: javascriptquotError No QueryClient setuse QueryClientProvider to set onequotStack Overflow