Home > database >  Data fetching from graphql server with ApolloClient doesn t work. How can I fix it?
Data fetching from graphql server with ApolloClient doesn t work. How can I fix it?

Time:03-28

Here, I am creating new ApolloClient with graphql

import { ApolloClient, InMemoryCache } from "@apollo/client"

const client = new ApolloClient({
    uri: "http://localhost:4000/graphql",
    cache: new InMemoryCache()
})

export default client

Then I create a context of ApolloProvider

import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import {ApolloProvider} from "@apollo/client"
import client from "./common/apollo-client"
import { Provider } from 'react-redux';
import store from "./redux/index"
import { BrowserRouter } from 'react-router-dom';

ReactDOM.render(
  <ApolloProvider client={client}>
    <Provider store={store}>
        <BrowserRouter>
          <App />
        </BrowserRouter>
    </Provider>
  </ApolloProvider>,
  document.getElementById('root')
);

Here is making a query in playground on https://localhost:4000/graphql

Here the same query in code

import { gql, useQuery } from "@apollo/client"

const GET_CATEGORIES = gql`
    {
        categories {
            name
        }
    }
`

export default function useGetCategories() {
    const {data} = useQuery(GET_CATEGORIES)
    return data
}

Then I trying to use this hook in a functional component, but it logs UNDEFINED

export default function Mainpage() {
    const categories = useGetCategories()

    console.log(categories)
    

    return (
        <Header />
    )
}

I tried to restart backend on localhost:4000, but it didn't help. What can I do about it?

CodePudding user response:

the problem is with you are using customHook and that is the promise for graphql what it does is return the instance of that current runtime and it is undefined at that time all you can do is simply use in the component that you want to use why are you complexing things.

export default function Mainpage() {
    const {loading,data,error} = useQuery(GET_CATEGORIES)
    // first data will be undefined and when the promise resolved it will console data
    console.log(data,{data})
    console.log(loading,{loading})
    console.log(error,{error})
    
    return (
        <Header />
    )
}

but if you still want to use customHook for graph you can do it like this.

  const [getCategories] = useLazyQuery(
    GET_CATEGORIES
  );
  const [data, setData] = useState()

  useEffect(async() => {
    try {
      const res = await getCategories()
      setData(res)
    } catch (err) {
      console.log('error: ', err)
    }
  }, [])

  return data
  • Related