The Apollo Client query returns unexpected null values even though the GraphQL Playground is successfully returning valid

After successfully adding a user to my database, I am encountering an issue where the query returns null in my client app even though it shows data in the GraphQL playground. To troubleshoot this problem, I have implemented a useEffect hook that triggers the query after the addPartner mutation is completed and data is received. However, I am puzzled as to why the query result is different between the playground and my application.

The addPartner function

  const handleSubmit = async (): Promise<void> => {
    ...
    await addPartner({ variables: { input: { ...form } } })
  }

My useEffect hook and query function

const [addPartner, { data, error: addPartnerError }] = useMutation(ADDPARTNER)
const [fetchPartner, { data: partnerData, loading }] = useLazyQuery<IPartner>(GETPARTNER)

  useEffect(() => {
    checkSuccess()
    console.log(partnerData) // null
  }, [data, loading])

  const checkSuccess = () => {
    if (!addPartnerError) {
      fetchPartner({ variables: { email: form.email } })
      console.log("fetch executed") // "fetch executed"
      console.log(partnerData) // null
      if (partnerData?.getPartner != null) {
        setPartner(partnerData.getPartner)
        router.replace('/success')
      }
    }
  }

Answer №1

It appears that the situation is more intricate than necessary. One key issue is that fetchPartner is a promise, yet you are not awaiting it in your checkSuccess function, resulting in null data initially. Additionally, your useEffect relies on loading, which triggers the query itself.

There are various simpler approaches you can take:

  1. Return the object being inserted as a result of the mutation to avoid making two network requests and receive the response immediately.
  2. Return the parent object of the mutated item. This method is preferable when adding or removing items from a list since it allows for a complete array refresh while maintaining its correct sequence.
  3. Trigger your query after the mutation using refetchQueries. For example:
const [addPartner, { data, error: addPartnerError }] = useMutation(ADDPARTNER,{
  refetchQueries: ['GETPARTNER'] 
})

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

Oops! Next.js Scripts encountered an error: Module '../../webpack-runtime.js' cannot be located

Looking to develop an RSS script with Next.js. To achieve this, I created a script in a subfolder within the root directory called scripts/ and named it build-rss.js next.config.js module.exports = { webpack: (config, options) => { config.m ...

Why does the width of my image appear differently on an iPhone compared to other devices?

I recently encountered an issue with the responsiveness of an image on my website. While it displayed correctly on Android and desktop devices, the image appeared distorted on iPhones as if the CSS width attribute was not applied properly. This problem spe ...

Saving data submitted through a form using React Hooks and JSON encounters problems with proper storage

I am facing an issue with a form that is supposed to create items labeled as "post" with unique IDs, titles, authors, and content. The desired structure is as follows: { "posts": [ { "id": 1, "title": "F ...

Next.js fails to extract variables from the .env file

I am encountering an error when trying to utilize a variable from the .env file. The error message is shown below: Uncaught (in promise) IntegrationError: Please call Stripe() with your publishable key. You used an empty string. code import Stripe from &q ...

Using Axios and Typescript to filter an array object and return only the specified properties

I'm currently working on creating an API to retrieve the ERC20 tokens from my balance. To accomplish this, I am utilizing nextjs and axios with TypeScript. However, I'm encountering an issue where the response from my endpoint is returning exces ...

Tips for selecting content for rendering with GetServerSideProps

Is there a way to display different text before and after a specific time without revealing all the content in the HTML? I've attempted using if-else logic within the component, but it ends up exposing text that should be hidden. Can getServerSideProp ...

Having trouble replacing scss variables in react-h5-audio-player

I recently integrated react-h5-audio-player into my project and followed the instructions on the README page to customize the styles by updating the SCSS variables that control the colors. However, it appears that my custom styles are not being applied. An ...

Encountered a snag with the getStaticProps() function in my Next.js project

I encountered an issue with my Next.js project: Error: page / getStaticProps cannot be attached to a page's component and must be exported from the page. More information can be found here: https://nextjs.org/docs/messages/gssp-component-member I sim ...

The useParams() function will return an empty value upon the component's initial render

I'm utilizing React along with the following libraries: "babel-eslint": "10.0.3", "react": "^17.0.2", "react-dom": "^17.0.2", "react-redux": "^7.2.4", "react-router-dom": "^6.3.0", "react-scripts": "3.2.0", "redux": "^4.1.1 ...

Can you use React Hooks to implement refs for ScrollView within a functional component?

Currently, I am in the process of transitioning a react native project from utilizing all class components to functional components with hooks. One of the challenges I am facing is converting a messaging page that includes a ScrollView functionality for ...

The nested grid containers and items are overflowing off the screen when using material UI react

I am attempting to create a user interface similar to the one shown below, but I am facing some difficulties in achieving the desired outcome. I have experimented with adjusting the columns as well, but that didn't yield the expected results either. ...

Encountering: error TS1128 - Expecting declaration or statement in a ReactJS and TypeScript application

My current code for the new component I created is causing this error to be thrown. Error: Failed to compile ./src/components/Hello.tsx (5,1): error TS1128: Declaration or statement expected. I've reviewed other solutions but haven't pinpointed ...

Encountering a "Module not found" error while trying to run npm start in a Create React App

I'm attempting to initiate a React project using create-react-app. Encountered an error when running npm start: Failed to compile. multi ./node_modules/react-scripts/config/polyfills.js ./node_modules/react-dev-utils/webpackHotDevClient.js ./src/i ...

Putting an <input/> element inside a Material UI's <TextField/> component in ReactJS - a beginner's guide

I am attempting to style <TextField/> (http://www.material-ui.com/#/components/text-field) to resemble an <input/>. Here is what I have tried: <TextField hintText='Enter username' > <input className="form-control ...

The onClick function is not functioning properly when trying to navigate to the next page. Can anyone help identify what might be missing in

I'm struggling with my showNextPage function and can't figure out why it's not working as expected. The goal is for the function to update the state, generate a new array of items, and display the next project in the array when clicked. Alth ...

Is it possible to leverage the flex features of react-native in a manner similar to the row/column system of

Is it a good idea to utilize flex in react native by creating custom components that retrieve flex values? I previously used the bootstrap grid system and now I am exploring react native. Is there a way to implement this example using react-native bootstr ...

To interact with Cognito in a React application, it is essential to provide the necessary Username and Pool

I'm currently working on creating a demo app using Cognito with React. I've been trying out the code available in this GitHub repository to experiment with it. However, I keep encountering the error message Username and Pool information required ...

The request made to `http://localhost:3000/auth/signin` returned a 404 error, indicating that

My goal is to access the signin.js file using the path http://localhost:3000/auth/signin Below is my code from [...nextauth].js file: import NextAuth from "next-auth" import Provider from "next-auth/providers/google" export default N ...

Guide: Passing and reading command line arguments in React JavaScript using npm

When launching the react application, I utilize npm start which is defined in package.json as "start": "react-scripts start -o". Within the JavaScript code, I currently have: const backendUrl = 'hardCodedUrl'; My intention ...

Ways to customize the TextInput component in React-Admin

I am facing a challenge with overriding specific fields in my custom theme. It seems that setting the custom theme also overrides other fields unintentionally. I attempted to use useStyles to resolve this issue, but unfortunately, it did not work as expec ...