What is the process for retrieving the variables associated with the ID from a different queried mapped loop's ID?

My goal is to fetch the userId from another nested map within a queried loop.

The issue encountered reads as follows: Error: Rendered more hooks than during the previous render.

This error cropped up when I inserted the following code snippet inside the map:

const { data: { getUser } = {} } = useQuery(FETCH_USER_QUERY, {
          variables: {
            userId: something?.id,
          },
        });

within my component... Below is my complete component code:

export default function SomethingComponent() {
  const { data: { getSomething } = {} } = useQuery(
    FETCH_SOMETHING_QUERY
  );

  return (
    <>
      {getSomething?.map((something) => {
        const { data: { getUser } = {} } = useQuery(FETCH_USER_QUERY, {
          variables: {
            userId: something?.id,
          },
        });
        return (
          <div>
            <h1>{getUser.name}</h1>
            {/* ... */}
            {/* ... */}
            {/* ... */}
            {/* ... */}
            {/* ... */}
            {/* ... */}
          </div>
        );
      })}
    </>
  );
}

Additionally, here is the query for fetching "Something":

const FETCH_SOMETHING_QUERY = gql`
  {
    getSomething {
      id
    }
  }
`;

As for the user query:

const FETCH_USER_QUERY = gql`
  query ($userId: ID!) {
    getUser(userId: $userId) {
        # ...
    }
  }
`;

I've pondered on possible resolutions, but I haven't found an alternative way to access something.id without delving into the mapped loop. Research suggests that the error may be due to improper placement or ordering of hooks.

Answer №1

You've violated the guidelines for using hooks by breaking the rules of hooks.

To resolve this issue, you should utilize the useApolloClient hook to manually execute the queries.

When it comes to retrieving users individually, there are two possible approaches we can take.

The first approach involves fetching the initial data, then utilizing the useEffect hook with the client extracted from useLazyQuery, and finally setting the state one by one (although this method may be considered complex):

The following code is just a suggestion. Copying and pasting it may not guarantee its functionality.

// Insert your previous code here
const [users, setUsers] = useState([])
const {
  client
} = useApolloClient()

useEffect(() => {
  if (getSomething.length > 0) {
    getSomething.forEach(async({
      id: userId
    }) => {
      const {
        data: newUsers
      } = await client.query({
        query: FETCH_USER_QUERY,
        variables: {
          userId,
        },
      })
      setUsers([...users, ...newUsers])
    })
  }
}, [getSomething])

The second approach is to divide the component into smaller components with fetching logic embedded within:

export default function SomethingComponent() {
  const { data: { getSomething } = {} } = useQuery(
    FETCH_SOMETHING_QUERY
  );

  return (
    <>
    {getSometing.map((user) => <UserComponent userId={user.id} />)}
    </>
  );
}

// UserComponent.js
export default function UserComponent({ userId }) {
  const { data: { user } = {} } = useQuery(
    FETCH_USER_QUERY, { variables: { userId } }
  );

  return (
    <>
    {user?.name}
    </>
  );
}

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

Unlocking Node.js packages within React JS is a seamless process

Currently, I am developing a React Serverless App with AWS. I am looking for ways to incorporate a Node JS specific package into the React JS code without requiring Node JS on the backend. One package that I need access to is font-list, which enables list ...

What is the best way to access a ViewChild element in the parent component without rendering it?

I am currently utilizing a component within another component in the following manner: <inline-help> <help-title>{{::'lang.whatIsThis'|i18n}}</help-title> <help-body i18n="lang.helpBody">& ...

Is it possible to submit a form through a JavaScript hotkey?

Here's the current code that I'm working with: <select tabindex="2" id="resolvedformsel" name="resolved"> <option selected="selected" value="yes">resolved</option> <option value="no">not resolved</option> ...

Combining multiple snippets of CSS classes in Material UI Emotion/Styled: How to do it effectively?

In previous versions, Material UI styled components allowed for the use of the className property to selectively apply styles. For example, a component could be styled like this: const styles = (theme: ThemeType) => ({ root: { width: '1 ...

Editable content tag

Is there a way to set the maximum number of rows in the contenteditable attribute? I would like to limit users once they reach the character capacity for sending data via POST method. I am currently working with HTML 5. Contenteditable is a new attribute ...

Ways to extract the source code of a webpage that has been modified on load

While working on extracting data from a website (completely within legal boundaries), I encountered an interesting situation. This particular site has 5 questions with answers on each page. However, upon inspecting the source code by pressing Ctrl+U, I no ...

Unable to submit form information

My Bootstrap form includes multiple fields that need to be filled out by the user. When the form is submitted, I want it to send data to a WebService. However, the user input data from the form is not being sent. Here is the HTML code: <form class="fo ...

Instructions on finding and inputting text into a textarea using python and javascript

Hello there, I've been experimenting with writing text inside a textarea element using Python Selenium and JavaScript: The JavaScript code I'm using is: self.driver.execute_script("document.getElementsByClassName('textarea').value ...

Once the eventListener function finishes, the content within the <div> element disappears

My HTML code is below and the output will be a string. <div id="response_container"> // Output will be stored here </div> Below is the JavaScript code const form = document.getElementById('search_form'); const htmlcontainer ...

Sending an AJAX request with an unpredictable quantity of parameters

I built a form for my website that pulls questions from a database based on certain variables. This means the number of questions available is unknown. The code snippet for displaying these questions looks like this: HTML <ol class="questions"> ...

Error encountered in connecting to PostgreSQL while accessing the Payload cms

Software Version Information "payload": "^2.0.0" Environment Details node:18.8-alpine Framework Version "next": "13.5.2" Issue Detected When attempting to run yarn build, the following error occurred: [12:41:39] ERROR (payload): Error: unable to connect ...

javascript/typescript - conditionally adding an item to an object

If I have an object called userData = {..} and I need to create another object, userDataB, with properties a, b, c, and d from userData but only if they are defined. One way to achieve this is by using the following approach: userDataB = {} if(userData.a ...

What is the best practice for using templates in a constructor versus connectedCallback?

Should I apply template in the constructor or connectedCallback of a custom element? In my experience, when I apply it in connectedCallback, sometimes attributeChangedCallback is called before and I can't query for elements. export class TestElement ...

Is there a reason for the absence of the Revit category attribute in the JSON response retrieved from the GET request :urn/metadata/:guid/

After receiving the information from the endpoint regarding Revit Models uploaded to my bucket, I noticed that the JSON response contains multiple objects. These objects seem to represent Revit elements, each with all parameters except for the Revit Categ ...

Is it possible for jQuery to fail within an object method?

Consider this scenario: function Schedule (foo) { this.foo = foo; this.bar = function() { $.ajax({ url: '/something/', method: "GET", dataType: "JSON" }).done (function(data){ ...

I wasn't able to use the arrow keys to focus on the select box in my table, but I had no problem focusing on all

I'm a novice in jQuery and I encountered a situation where I have select boxes and text fields within my table. I successfully implemented arrow key functionality (down for next, up for prev) for shifting focus to the field by assigning classes to eac ...

Manipulating attributes in HTML using jQuery which are stored in a variable

Generating dynamic inputs with unique names is my current requirement. Initially, I store the html template content in a variable: var template = $("#question_template").html(); Next, to differentiate each set of added input blocks, I include an index: ...

Sending a photo to digital ocean via the s3Client

I'm having trouble uploading an image to Digital Ocean Spaces. Here is my client-side code: const formData = new FormData(); formData.append('myFile', file as string) fetch('/api/upload', { method: 'POST' ...

Exploring the capabilities of qTip2 integrated with jQuery Vector Maps (jqvmap)

Is there a way to disable the default tooltip in jqvmap and replace it with qTip2? Check out this example. Here's the jQuery code: jQuery('#vmap').vectorMap({ map: 'world_en', backgroundColor: null, color: '#ffff ...

Create a cylindrical HTML5 canvas and place a camera view inside the cylinder

I have a unique project in mind that involves creating an HTML5 canvas cylinder with the camera view at its center. The walls of the cylinder will display images, and the entire structure should be able to rotate and zoom. If anyone has any advice on how ...