Utilizing a custom hook alongside another hook in React - a streamlined approach?

I am currently developing an app using React with next.js.

There is a GraphQL query that I need to run in order to retrieve some data, but I seem to be encountering some issues.

When I use the useQuery hook as shown below, it successfully returns the response:

import { useQuery } from 'react-apollo';

export function LaunchesFunctionTwo() {
  const { loading, error, data } = useQuery(GET_SUBSCRIPTION_BY_ID)

  // The data is logged correctly here
  console.log(data)

  // Since I only require the data without displaying it, I am returning an empty string
  // This raises another question - how can I solely utilize the useQuery hook itself?
  return ''
 
}

However, when I implement the same code in the Index component, the console.log(data) outputs undefined:

import { useQuery } from 'react-apollo';

export default function Index(props) {
  const { loading, error, data } = useQuery(GET_SUBSCRIPTION_BY_ID)

  // Consequently, the returned data is undefined
  console.log(data)

   return (<div>...</div>)
}

UPDATE: I have managed to resolve this issue. After reading that Hooks should only be used in specific ways, one being "Call Hooks from custom Hooks," I created a custom hook like so:

According to the documentation, the use keyword is necessary:

export function useLaunchesFunctionTwo() {
  const { loading, error, data } = useQuery(GET_SUBSCRIPTION_BY_ID)

  return data
}

Now, in my index.js file, I simply invoke the useLaunchesFunctionTwo to obtain the desired data.

The question remains - is this a valid approach? Could I have structured my code in a more organized manner?

Any assistance would be greatly appreciated.

Answer №1

It seems that you have forgotten to include the useQuery import statement in your Index file.

import { useQuery } from 'react-apollo';

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Transmitting confidential information to the Next.js Link module

One aspect I'm curious about is the Link component from 'next-Link'. If I need to pass sensitive data, such as a category_id, how can I securely transmit it for use in the getServerSideProps() function without relying on query strings? ...

What are the steps for positioning material-ui icons to the right?

I have a list that is dynamically generated with the following code snippet: <list className = "todos-list"> {allTodos.map((todo, index)=> { return ( ...

What is the best way to preserve the state of an array while updating another state with setState?

I'm endeavoring to devise a ButtonGroup that allows for multiple buttons to be clicked simultaneously. The goal is for a button to change color upon being clicked, while its value is added to an array. Ideally, if three buttons are clicked, the array ...

Docker containers do not allow environment variables to be overridden

I am relatively new to Docker and I have a Nextjs application running inside a docker container. This application utilizes certain environment variables for communication with the server. An issue arises where, despite passing the environment variables whe ...

Challenges with Apollo GraphQL: Struggling to get the GraphQLWsLink (Subscriptions) to work with Next.js due to issues with the WebSocket implementation

Recently, I set up a GraphQL server in Go by following a tutorial closely. My front-end is developed using Next.js and I'm currently working on creating a client to connect to the server. Despite referring to the subscription docs thoroughly, I can&ap ...

Is it possible to pass multiple parameters in one onClick event?

My search bar is located below. Upon clicking the 'search' button, I wish for it to update results and redirect to a different page simultaneously. function SearchBar(props) {   const [innerSearch, setInnerSearch] = useState(""); ...

Using React components with Material UI to create styled div boxes

As I work on creating a mock website with React and Material UI, I have utilized the RaisedButtonExampleSimple component for buttons from Material UI within a div named App-Intro. Strangely, the text in the Div "Customer-Choice" is displaying above the but ...

Ways to refresh the session on the server end

What is the process for updating a session in the server side using authV5 in the most recent update of nextjs? I have attempted the following: import { update } from "@/auth However, I am unable to locate the update function within the auth module ...

Encountering a problem with the React version. Upgrading to a newer version

I've been facing issues with installing the latest version of react. Even after trying different methods like appending @ to specify a particular version or completely uninstalling nodejs, it still doesn't work. npm react --version 6.14.15 When ...

What are some ways to implement dangerouslySetInnerHTML in conjunction with read-more-react from npm?

Is there a way to include dangerouslySetInnerHTML in a text field without receiving an error? <ReadMoreReact text={yourTextHere} min={minimumLength} ideal={idealLength} max={maxLength} readMoreText={read ...

"Successfully rendering the map on the initial load, but encountering an error of 'cannot map undefined'

Having trouble displaying data retrieved from an API. Initially, the movie titles are shown without any issues. However, upon refreshing the page, an error message stating "cannot map undefined" appears. Here is the code snippet: const [media, set ...

The error message "Encountered an issue when trying to access properties of undefined (reading 'getState')" was

Currently working on developing an app that utilizes a Django backend and React frontend. The goal is to enable users to log in, receive refresh and access tokens from Django, store the token in local storage, and redirect authenticated users to a static p ...

Material UI Grid List rows are displaying with an unusually large gap between them, creating a

Currently, I am utilizing Material UI in combination with Reactjs. One particular issue that I am encountering involves the Grid List Component. In my attempt to establish a grid of 1000x1000px, I have specified the height and width within the custom gridL ...

Double invocation of useEffect causing issues in a TypeScript app built with Next.js

My useEffect function is set up with brackets as shown below: useEffect(() => { console.log('hello') getTransactions() }, []) Surprisingly, when I run my app, it logs "hello" twice in the console. Any thoughts on why this might be ...

What is the correct way to run npm and node on Windows 11? I keep encountering an error when attempting to execute npm install on my Windows system

I am encountering an error message when attempting to execute npm install or npm install nodejs-java on my Windows 11 system. Here are the versions: npm version - 9.6.1 node version - v18.15.0 Visual studio - 2017 Despite multiple attempts, I have been u ...

Using Redirects in React JS

I'm attempting to change the route when a certain condition is met. I've included 'useNavigate' from react-router-dom, but it's not functioning as expected. import { useNavigate } from "react-router-dom"; const navigate = ...

When running Nextjs locally, Sendgrid functions seamlessly. However, when I deploy it on Vercel, Sendgrid

I've successfully tested this locally, but encountered a "Response Error: Unauthorized" when deploying on Vercel. After creating and verifying a Single Sender Verification on Sendgrid, I attempted to generate a new API key, but the issue persists. I ...

Having trouble getting Tailwindcss to work with Next.js - what could be causing the configuration issue?

Why is tailwind not displaying correctly in my next.js project? I'm concerned that there might be a problem with my settings. In the styles folder, I have a file called tailwind.css @tailwind base; /* Write your own custom base styles here */ /* S ...

Selecting menu items in React Material UI with various background colors using the RAL color selector component

Seeking a solution to create a component for selecting RAL colors using Material UI's TextField and MenuItem. Each item in the menu should have a background color reflecting the RAL color it represents. However, Material UI no longer supports inline s ...

What advantages could learning ReactJS first give me before diving into NextJS?

Just mastered TS and now faced with the decision of choosing a framework. I'm curious why it's recommended to learn ReactJS before NextJS. I've read countless articles advising this, but no one seems to delve into the reasons behind it. Ca ...