5

I am trying to figure out how to access the object.id on the update mutation I have made in my app.

I have an object called IssueGroup. I have made create and delete mutations and for the most part, they work okay. I'm getting stuck with the update mutation because I can't seem to get it to recognise the id of the object I'm trying to update.

I have a form with:

import * as React from "react"
import { gql } from "@apollo/client"
import type { IssueGroupInput } from "lib/graphql"
import { QueryMode, Role, SortOrder, useAllIssueGroupsQuery,  useDeleteIssueGroupMutation, useUpdateIssueGroupMutation  }  from "lib/graphql"
import { AdminCreateIssueGroupForm } from "components/AdminCreateIssueGroupForm"
import { AdminUpdateIssueGroupForm } from "components/AdminUpdateIssueGroupForm"
import { Modal } from "components/Modal"


const __ = gql`
  query AllIssueGroups {
    allIssueGroups {
      id 
      title
      description
    }
  }
  mutation deleteIssueGroup($id: String!) {
    deleteIssueGroup(id: $id) {
      id
      title
      description
      issues
    }
  }
`

export default function IssueGroups() {
  const [selectedIssueGroups, setSelectedIssueGroups] = React.useState<string[]>([])
  const modalProps = useDisclosure()
  const modalPropsUpdate = useDisclosure()
  const [deleteIssueGroup] = useDeleteIssueGroupMutation()
  const [updateIssueGroup] = useUpdateIssueGroupMutation()
  const { data: issueGroup, refetch: refetchAllIssueGroups } = useAllIssueGroupsQuery()


  const { data, loading, refetch } = useAllIssueGroupsQuery()
  const allIssueGroups = data?.allIssueGroups
  const onDeleteIssueGroup = (id: string) => {
    return (
     deleteIssueGroup({ variables: { id } }).then(() => refetch())
    )
  }
  return (
    <Box>
     
      <Wrap mb={4} spacing={2}>
        <Button
          onClick={modalProps.onOpen}
          
          }}
        >
          Create issue group
        </Button>
      </Wrap>

      <Modal {...modalProps} title="Create Issue Group">
        <AdminCreateIssueGroupForm onClose={modalProps.onClose} />
      </Modal>

                   <IconButton
                              onClick={modalPropsUpdate.onOpen}
                            
                          />
                          <Modal {...modalPropsUpdate} title="Update Issue Group">
                            <AdminUpdateIssueGroupForm onClose=
{modalPropsUpdate.onClose} />
                              </Modal>
    
                              <IconButton
                                  onClick={() => onDeleteIssueGroup(issueGroup.id)}
                                 
                              />
                           
                          ))}
                        
      )
    }
    
 

Then, I have a modal that opens when the update button is clicked that has:

import * as React from "react"
import { gql } from "@apollo/client"
import { useRouter } from "next/router"

import { useAllIssueGroupsQuery, useUpdateIssueGroupMutation, IssueGroupInput } from "lib/graphql"
import { useForm } from "lib/hooks/useForm"
import Yup from "lib/yup"


const _ = gql`
  query AllIssueGroups {
      allIssueGroups {
        id
        title
        description
        issues
      }
    }

  mutation updateIssueGroup($id: String!, $data: IssueGroupInput!) {
    updateIssueGroup(id: $id, data: $data) {
      id
      title
      description
      issues
    }
  }
`

interface Props {
  onClose: () => void
}

const IssueGroupSchema = Yup.object().shape({
 
  title: Yup.string().required(),
  description: Yup.string().required(),
})

export function AdminUpdateIssueGroupForm(props: Props) {
  const router = useRouter()
  const [updateIssueGroup] = useUpdateIssueGroupMutation()
  const { data: issueGroups, refetch: refetchAllIssueGroups } = useAllIssueGroupsQuery()

  
  const form = useForm({ schema: IssueGroupSchema })
  
  const handleSubmit = async(data:IssueGroupInput) => {
    console.log("made it to the handle submit before success handler")
    return await form.handler(() => updateIssueGroup({ 
      variables: { 
            id: issueGroup.id, 
            // I get an error that says  Cannot find name 'issueGroup'. Did you mean 'issueGroups'. 
            // I know that's because I'm using the AllIssueGroups query to find many, 
            // but I don't know how to write the query to find the specific one I 
            // want to edit when I press the edit button in the form above

            data: { ...data } 
      } }), {
      
      onSuccess: (res, toast) => {
        console.log("made it to the form handler success")
        
        toast({ description: "Issue group updated" })
        form.reset()
        props.onClose()
        
      },
    })
  }
  return (
    <Form {...form} onSubmit={handleSubmit}>
      <Stack>
        <Input  name="title" label="Title" />
       
        {/* <Input name="description" label="Description" /> */}
        {/* <Text mb='8px' fontWeight="medium" fontSize="sm" > Description</Text> */}
        <Textarea name="description" label="Describe" rows={4}/>
          <Button onClick={props.onClose}>Cancel</Button>
             type="submit"
          >
            Create
       </Form>
  )
}

My IssueGroup resolver has:

  @Mutation(() => IssueGroup)
    async updateIssueGroup(
        @Arg("id") id: string,
        @Arg("data") data: IssueGroupInput
    ) {
        return await this.issueGroupService.updateIssueGroup(id, data)
    }

 @Query(() => IssueGroup)
    async issueGroup(@Arg("id") id: string) {
        return await this.issueGroupService.getIssueGroup(id)
    }

The IssueGroup service has:

async updateIssueGroup(id: string, data: IssueGroupInput) {
    const issueGroup = await prisma.issueGroup.findUnique({ where: { id } })
    if (!issueGroup) {
      throw new Error("Issue not found")
    }
    return await prisma.issueGroup.update({ where: { id }, data })
  }



async getIssueGroup(id: string) {
    return await prisma.issueGroup.findUnique({
      where: {
        id,
      },
    })
  }

How can I tell the modal form for update what the specific issueGroup.id related to the button clicked to open the modal is?

The prisma schema has:

model IssueGroup {
  id              String @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
  title           String
  description     String
  issues          Issue[]
  createdAt       DateTime @default(now()) @db.Timestamptz(6)
  updatedAt       DateTime @default(now()) @updatedAt @db.Timestamptz(6)
}

model Issue {
  id              String      @id @default(dbgenerated("gen_random_uuid()")) @db.Uuid
  title           String
  description     String
  issueGroup      IssueGroup?  @relation(fields: [issueGroupId], references: [id], onDelete: SetNull, onUpdate: Cascade)
  issueGroupId    String?      @db.Uuid
  subscribers     UserIssue[]
  createdAt       DateTime    @default(now()) @db.Timestamptz(6)
  updatedAt       DateTime    @default(now()) @updatedAt @db.Timestamptz(6)
}

NEXT ATTEMPT

I have made a further attempt, which tries to give the modal the issueGroup.id with the onClick handler, but I still can't get the form to recognise the id, and this version of this attempt generates an error message I don't know how to break down. It says:

Type '{ onClose: () => void; issueGroup: Omit<IssueGroup, "createdAt" | "updatedAt" | "issues"> | null; }' is not assignable to type 'IntrinsicAttributes & Props'. Property 'issueGroup' does not exist

on type 'IntrinsicAttributes & Props'.

This time:

  • I tried to set state:

     import { QueryMode, Role, SortOrder, useAllIssueGroupsQuery,  useDeleteIssueGroupMutation, useUpdateIssueGroupMutation, IssueGroup as IssueGroupGQLType  }  from "lib/graphql"
    
      const [selectedIssueGroup, setSelectedIssueGroup] = React.useState<Omit<
          IssueGroupGQLType,
          "createdAt" | "updatedAt" | "issues" 
        > | null>(null)
    
  • the update button has:

    <IconButton
                                      aria-label='Update Issue Group'
                                      // onClick={modalPropsUpdate.onOpen}
                                      onClick={() => {
                                        setSelectedIssueGroup(issueGroup)
                                        modalPropsUpdate.onOpen()
    
                                  <Modal {...modalPropsUpdate } title="Update Issue Group">
                                    <AdminUpdateIssueGroupForm onClose={modalPropsUpdate.onClose} issueGroup ={selectedIssueGroup}  />
                                  </Modal>
    

Then, in the form, I tried to read issueGroup.id:

const _ = gql`
  query AllIssueGroups {
      allIssueGroups {
        id
        title
        description
        issues
      }
    }

  mutation updateIssueGroup($id: String!, $data: IssueGroupInput!) {
    updateIssueGroup(id: $id, data: $data) {
      id
      title
      description
      issues
    }
  }
`

interface Props {
  onClose: () => void

  issueGroup: selectedIssueGroup
}

const IssueGroupSchema = Yup.object().shape({
 
  title: Yup.string().required(),
  description: Yup.string().required(),
})

export function AdminUpdateIssueGroupForm(props: Props) {
  const router = useRouter()
  const [updateIssueGroup] = useUpdateIssueGroupMutation()
  // const { data: issueGroups, refetch: refetchAllIssueGroups } = useAllIssueGroupsQuery()

  
  const form = useForm({ schema: IssueGroupSchema })
  
  const handleSubmit = async(  data:IssueGroupInput) => {
    // await form.triggerValidation()
    console.log("made it to the handle submit before success handler")

The variables below don't know what issueGroup is

    return await form.handler(() => updateIssueGroup({ variables: { id: issueGroup.id,  data: { ...data } } }), {
      
      onSuccess: (res, toast) => {
        console.log("made it to the form handler success")
        
        form.reset()
        props.onClose()
        
      },
    })
  }
  return (
    <Form {...form} onSubmit={handleSubmit}>
      <Stack>
        <Input  name="title" label="Title" />
       
        <Textarea name="description" label="Describe" rows={4}/>
       
        <FormError />
        <ButtonGroup>
          <Button onClick={props.onClose}>Cancel</Button>
          <Button
           
             type="submit"
            isLoading={form.formState.isSubmitting}
            isDisabled={form.formState.isSubmitting}
          >
            Create
          </Button>
        </ButtonGroup>
      </Stack>
    </Form>
  )
}

With this attempt, my form still doesnt know what selectedIssueGroup or IssueGroup mean.

I have seen this page of the react docs, and I think the bit I am missing is that I haven't wrapped my form in the equivalent of isActive. The problem is, I don't know where to put selectedIssueGroup. My definition of that state is in a different file to the file the form is is saved in.

In an attempt to apply the logic in this documentation, I tried changing the modal so that is wrapped inside the state, as follows:

{selectedIssueGroup &&
                              <Modal {...modalPropsUpdate } title="Update Issue Group">
                              <AdminUpdateIssueGroupForm onClose={modalPropsUpdate.onClose} issueGroup ={selectedIssueGroup}  />
                              </Modal>
                            }

I don't get any new errors, but it also doesn't work. My form still doesn't know what the issueGroup is.

I can see that the update button knows what the issueGroup is and I can see that the Modal knows it too. I cant figure out how to give that value to the update form.

enter image description here

I have seen this tutorial, which shows how to use the create form to make an edit. The screen shot it uses displays the created information populated in the edit form, but it does not show how it found that data to use in that form. I can't find an example of how to do that.

NEXT ATTEMPT 21 DEC

In this most recent attempt, I have tried to add the issueGroup reference as a property on the Modal. Even if this worked, I think it would not be helpful for a reason explained below. However, i don't understand why it doesn't work.

<Modal {...modalPropsUpdate } issueGroup={selectedIssueGroup} title="Update Issue Group"  >

When I try this, I get an error (VS code underlines the issueGroup in the above line). The error message says:

Type '{ children: (void | Element)[]; issueGroup: Omit<IssueGroup, "createdAt" | "updatedAt" | "issues"> | null; title: string; isOpen:

boolean; onOpen: () => void; ... 4 more ...; getDisclosureProps: (props?: any) => any; }' is not assignable to type 'IntrinsicAttributes & Props & { children?: ReactNode; }'. Property 'issueGroup' does not exist on type 'IntrinsicAttributes & Props & { children?: ReactNode; }'.

I don't know what this means. The console logs inside the update button, and above and below the modal all know what issueGroup is.

The reason I think it is not required is that I can log the value of the issue Group above the modal and above the component inside the modal that loads the form. Both logs show the value of the issueGroup that I want to use in the form.

I'm trying to do that as follows:

const CheckIfModalKnowsIssueGroupId = props => {
  console.log("checking if modal knows the issue group", props.toLog);
  return (
    <div>
      {props.children}
    </div>
  );
};

ALTERNATE for attempt to log inside the form component

<AdminUpdateIssueGroupForm 
 onClose={modalPropsUpdate.onClose} 
 issueGroup ={selectedIssueGroup} 
>
  <CheckIfModalKnowsIssueGroupId toLog={selectedIssueGroup} />
    
</AdminUpdateIssueGroupForm>

NEXT ATTEMPT - READ MODAL VALUES

In a further attempt to try and make the modal carry the value of IssueGroup, I am trying to do the following:

{selectedIssueGroup  &&  modalPropsUpdate(isOpen:true) <Modal {...modalPropsUpdate } issueGroup={selectedIssueGroup} title="Update Issue Group"  >

This attempt is wrong because I don't know how to engage with modalPropsUpdate. The above formulation generates an error in the isOpen test as follows:

const modalPropsUpdate: {
    isOpen: boolean;
    onOpen: () => void;
    onClose: () => void;
    onToggle: () => void;
    isControlled: boolean;
    getButtonProps: (props?: any) => any;
    getDisclosureProps: (props?: any) => any;
}

This expression is not callable. Type '{ isOpen: boolean; onOpen: () => void; onClose: () => void; onToggle: () => void; isControlled: boolean; getButtonProps: (props?: any) => any; getDisclosureProps: (props?: any) => any; }' has no call signatures.

I can't find syntax that does not produce an error.

The objective of this attempt is to see if the modal is open, and still knows what the selectedIssueGroup is.

NEW OBSERVATION

I have seen this repo. I cannot find an example using the structure I have adopted to allow the id to be communicated to the form.

NEXT ATTEMPT 23 DEC

I tried to rule out the source of the problem as the selectedIssueGroup state handler being set in a different component to the form I was trying to use to update the object. So, I moved the form into the same file. It did not work. The udpate form handler still does not know what issueGroup.id or selectedIssueGroup mean.

import * as React from "react"
import { gql } from "@apollo/client"
import { useRouter } from "next/router"
import type { IssueGroupInput } from "lib/graphql"
import { QueryMode, Role, SortOrder, useAllIssueGroupsQuery,  useDeleteIssueGroupMutation, useUpdateIssueGroupMutation, IssueGroup as IssueGroupGQLType  }  from "lib/graphql"
// , 
import { AdminCreateIssueGroupForm } from "components/AdminCreateIssueGroupForm"
import Yup from "lib/yup"


const __ = gql`
  query AllIssueGroups {
    allIssueGroups {
      id 
      title
      description
    }
  }

  mutation updateIssueGroup($id: String!, $data: IssueGroupInput!) {
    updateIssueGroup(id: $id, data: $data) {
      id
      title
      description
      issues
    }
  }
`

const CheckIfModalKnowsIssueGroupId = props => {
  console.log("checking if modal knows the issue group", props.toLog);
  return (
    <div>
      {props.children}
    </div>
  );
};



const IssueGroupSchema = Yup.object().shape({
 
  title: Yup.string().required(),
  description: Yup.string().required(),
})


  
  const form = useForm({ schema: IssueGroupSchema })
  
  
  



export default function IssueGroups() {
  const [selectedIssueGroups, setSelectedIssueGroups] = React.useState<string[]>([])
  const modalProps = useDisclosure()
  const modalPropsUpdate = useDisclosure()
  const [deleteIssueGroup] = useDeleteIssueGroupMutation()
  const { data: issueGroup, refetch: refetchAllIssueGroups } = useAllIssueGroupsQuery()
  const [selectedIssueGroup, setSelectedIssueGroup] = React.useState<Omit<
    IssueGroupGQLType,
    "createdAt" | "updatedAt" | "issues" 
  > | null>(null)
  

  interface Props {
  onClose: () => void
  issueGroup: typeof selectedIssueGroup
}
function AdminUpdateIssueGroupForm(props: Props) {
  const router = useRouter()
  const [updateIssueGroup] = useUpdateIssueGroupMutation()
 
  
const handleSubmitUpdate = async(  data:IssueGroupInput) => {
    // await form.triggerValidation()
    console.log("made it to the handle submit before success handler")
    return await form.handler(() => updateIssueGroup({ variables: { id: issueGroup.id,  data: { ...data } } }), {
      
      onSuccess: (res, toast) => {
        console.log("made it to the form handler success")
        
        toast({ description: "Issue group updated" })
        form.reset()
        props.onClose()
        
      },
    })
  }
  
  const { data, loading, refetch } = useAllIssueGroupsQuery(
  
  )

  
  const allIssueGroups = data?.allIssueGroups

  const onDeleteIssueGroup = (id: string) => {
    return (
     deleteIssueGroup({ variables: { id } }).then(() => refetch())
    )
  }
  return (
      
      <Wrap mb={4} spacing={2}>
        <Button
          onClick={modalProps.onOpen}
                  >
          Create issue group
        </Button>
      </Wrap>

      <Modal {...modalProps} title="Create Issue Group">
        <AdminCreateIssueGroupForm onClose={modalProps.onClose} />
        
      </Modal>

                    {data?.allIssueGroups.map((issueGroup) => (
                      <Tr key={issueGroup.id}>
                      
                       <Text textStyle="h6">{issueGroup.title}</Text>
                            <IconButton
                                onClick={() => {
                                  setSelectedIssueGroup(issueGroup)
                                  modalPropsUpdate.onOpen()
                                }}
                               
                            />
                          {  console.log("update knows what the issuegroup is", selectedIssueGroup)}

                          <Modal {...modalPropsUpdate } title="Update Issue Group"  >
                              
                                <Form {...form} onSubmit={handleSubmitUpdate} >
          <Stack>
            <Input  name="title" label="Title" />
          
           
            <ButtonGroup>
              <Button onClick={props.onClose}>Cancel</Button>
              <Button
              
                type="submit"
               
              >
                Save changes
              </Button>
            </ButtonGroup>
          </Stack>
        </Form>
                              </Modal>
                            

                            <IconButton
                              onClick={() => onDeleteIssueGroup(issueGroup.id)}
                                                           />
                          </ButtonGroup>
                        

                          
      
Mel
  • 2,481
  • 26
  • 113
  • 273
  • Can you post the relevant parts of your GraphQL schema? And to be clear, the only error you are getting is `Cannot find name 'issueGroup'. Did you mean 'issueGroups'`? Is this error happening in your frontend, backend, or somewhere else? – Shea Hunter Belsky Dec 16 '22 at 23:56
  • hi @SheaHunterBelsky - I added the schema models to the end of the post. My vsCode underlines where i have added id: issueGroup.id and suggests I might want to use issueGroups, and when I try to load the page in local host, it loads, but the update form is a blank form that does nothing (it wont submit). In any event, it should be populated with the data entered when it was created. – Mel Dec 17 '22 at 00:03
  • @Mel What did **IssueGroups** component do.. I can see only data fetch using **useAllIssueGroupsQuery** but don't see any loop to render **issueGroup** data. How are you rendering *IssueGroups* component ?? – Zulqarnain Jalil Jan 02 '23 at 07:37
  • @ZulqarnainJalil - it's down the bottom. it's used to list all the issue groups – Mel Jan 02 '23 at 18:33

4 Answers4

0

From the code you posted for AdminUpdateIssueGroupForm, there isn't a variable defined as issueGroup here:

export function AdminUpdateIssueGroupForm(props: Props) {
  const router = useRouter()
  const [updateIssueGroup] = useUpdateIssueGroupMutation()
  const { data: issueGroups, refetch: refetchAllIssueGroups } = useAllIssueGroupsQuery()

  
  const form = useForm({ schema: IssueGroupSchema })
  
  const handleSubmit = async(data:IssueGroupInput) => {
    // await form.triggerValidation()
    console.log("made it to the handle submit before success handler")
    return await form.handler(() => updateIssueGroup({ 
      variables: { 
            // ========== issueGroup has not yet been defined ===========
            // ========== Do you need to pull anything out of the 'data' variable to get the right issueGroup variable? ===========
            id: issueGroup.id, 

If you are looking to update the data from a single issueGroup instance that derives from the issueGroups variable, it looks like it would derive from the data variable you defined at the handleSubmit function.

Shea Hunter Belsky
  • 2,815
  • 3
  • 22
  • 31
  • That's what I'm trying to figure out. IssueGroupInput is the source of data. That just has title and description. I don't know how to give the relevant id (which would be the issueGroup.id that is the key in the table that I have used to put the edit button – Mel Dec 17 '22 at 00:21
  • maybe i should replace the useAllIssueGroupsQuery with the singular IssueGroupQuery, but I still can't figure out how to tell it which issueGroup I want to update. – Mel Dec 17 '22 at 00:24
  • For your `
    ` in React, where are you getting data that allows a user to edit the _original_ element? How does the user actually specify the specific `Issue` that they are going to edit?
    – Shea Hunter Belsky Dec 17 '22 at 01:07
  • the page that has the edit button is inside a list of all the issueGroups, each one has its own id. When the user clicks the edit button, I want it to specify that id – Mel Dec 17 '22 at 01:24
  • You're going to have to use React state to track the ID of the issue being edited (in response to clicking on the Edit button.) Then when you submit your mutation to your backend, you can read the stateful variable from React state and pass it as part of the mutation – Shea Hunter Belsky Dec 17 '22 at 01:53
  • I posted a new attempt at the bottom of my post, but I think I am just pushing the same problem around the different components. I can't figure out how to give the id to the form – Mel Dec 17 '22 at 02:28
  • The problem still remains that you need some place (React state or something else) to track what issue a user wants to edit. If users cannot specify what issue they want to edit, then you will never be able to have the ID that you need. – Shea Hunter Belsky Dec 17 '22 at 02:41
  • That's what I'm trying to figure out how to do. – Mel Dec 17 '22 at 02:52
0

A typical pattern for a list in react with an onClick action on an item where you want to use the id is:

list.map(el => (
  <div key={el.id} onclick={() => clickHandler(el.id)>
    ... the rest of your layout
  </div>
)

where the clickHandler function is whatever function you want to run on click. That function should accept the object's id as a parameter. That function can in turn call the form's submit handler should you be using forms.

Michel Floyd
  • 18,793
  • 4
  • 24
  • 39
  • That's why I am confused as to why my form does not know what selectedIssueGroup or IssueGroup mean. I have defined them in the page and used them in the onClick handler – Mel Dec 17 '22 at 22:42
  • You have `handleSubmit = async( data:IssueGroupInput)` but then you have `onSubmit={handleSubmit}` - there's no actual passing of `data` into your `handleSubmit` function. – Michel Floyd Dec 18 '22 at 01:39
  • It's a variable in the handleSubmit. return await form.handler(() => updateIssueGroup({ variables: { id: issueGroup.id, data: { ...data } } }), { – Mel Dec 18 '22 at 02:20
  • Yes but `issueGroup.id` doesn't exist in the context of `handleSubmit`! – Michel Floyd Dec 18 '22 at 19:40
  • How can I bring it to existence? I also can't populate the form with the values originally created, so I'm clearly missing the chip, but I can't find a way to communicate with the form. – Mel Dec 18 '22 at 19:45
  • My attempt to make it exist is this statement: return await form.handler(() => updateIssueGroup({ variables: { id: issueGroup.id, data: { ...data } } }), { – Mel Dec 18 '22 at 20:05
  • Clearly, that's not enough because the file that this statement is written in does not know what either issueGroup or selectedIssueGroup mean. I can't find a way to communicate those values. I thought I was doing that with the onClick handler for update. Please can you give me a direction to a resource that can give me a clue about how to communicate between those two points. Thank you very much – Mel Dec 18 '22 at 20:06
  • Just FYI - this question is really hard to follow. You've got so much code in there which is not relevant to the question. One thing I did notice is that your Modal does not take the object that's being edited as a prop. – Michel Floyd Dec 20 '22 at 18:33
  • I know, but I'm leaving the background there to try and help someone else find a way through it if they are also stuck. The heading "Next Attempt" is where I'm up to. I'll move that to the top and put the previous attempts under another heading to make it clearer as to the current attempt – Mel Dec 20 '22 at 19:26
  • the modalPropsUpdate is a call to useDisclosure in react. That doesn't allow me to add the issueGroupId. The modal has the . I'm currently working on finding a way to try and console.log the value of issueGroup inside that block. I'm stuck on that step at the moment so I can't tell if it is properly communicate the value of the id. – Mel Dec 20 '22 at 19:39
0

I think your attempt 2 will work fine if you do this

You are setting a state and passing it to component like

<AdminUpdateIssueGroupForm onClose={modalPropsUpdate.onClose} issueGroup={selectedIssueGroup}  />

and getting the props in AdminUpdateIssueGroupForm like ,

function AdminUpdateIssueGroupForm(props: Props) {

so you should access issueGroup.id like this in form handler,

return await form.handler(() => updateIssueGroup({ variables: { id: props.issueGroup.id,  data: { ...data } } }), {

Note: In your last attempt also, you can access props.issueGroup.id

UPDATE:

for the selectedIssueGroup issue, i believe you are talking about the interface Props here.

In that interface you should provide a type to issueGroup not a state variable.So try this,

declare a type before usestate as

type IssueGroupType = Omit<
  IssueGroupGQLType,
  "createdAt" | "updatedAt" | "issues" 
> | null

and use it in both state and your interface

State:

const [selectedIssueGroup, setSelectedIssueGroup] = React.useState<IssueGroupType>(null)

interface:

interface Props {
  onClose: () => void
  issueGroup: IssueGroupType
}
Arjun
  • 1,181
  • 1
  • 1
  • 7
  • Hi @Arjun, thank you for the suggestion. When I try this, the vsCode doesn't underline the variable when I define it in the handler as you have described, but the Props doesn't know what selectedIssueGroup is. The error message on issueGroup: selectedIssueGroup still says cannot find name selectedIssueGroup – Mel Dec 26 '22 at 22:30
  • Hi @Mel, thanks for rewarding :) . I've updated my answer for the `selectedIssueGroup` issue. Please check. – Arjun Dec 27 '22 at 06:33
  • Thanks @Arjun. Thanks for the suggestion. I tried your approach and am getting the same error in the interface props. It says cannot find name IssueGroupType – Mel Dec 27 '22 at 06:48
  • can you update in your question how you are using that type ? – Arjun Dec 27 '22 at 06:53
  • I've used it as you have shown in your suggestion. I can't update the post - the character count has hit the max limit. – Mel Dec 27 '22 at 06:56
  • now, do you have `AdminUpdateIssueGroupForm` as a separate component ? (in a different file ?) – Arjun Dec 27 '22 at 06:58
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/250670/discussion-between-arjun-and-mel). – Arjun Dec 27 '22 at 07:02
  • I did, but I also tried duplicating everything and putting in n the same file (no separate component holding the form aspect). I still cant find a way to get the functions working. I posted the single file attempt in this post: https://stackoverflow.com/questions/74925142/prisma-graphql-and-react-hook-forms-how-to-use-created-values-in-update-form-m – Mel Dec 27 '22 at 07:04
  • Having separate component is good. You just have to import this type in that file. Connect in this chat to discuss more : https://chat.stackoverflow.com/rooms/250670/discussion-between-arjun-and-mel – Arjun Dec 27 '22 at 07:20
  • i tried adding it, but couldn't get it to work. I'll try again tomorrow. Thanks for your help – Mel Dec 27 '22 at 07:28
0

You need to create a separate handler for the Edit button and set some state, then just pass that state in editFormModal component like the code is given below. To test the code, you can click Here

export default function IssueGroups() {
  const toast = useToast()
  const [isOpen, setIsOpen] = useState(false);
  const [loadGreeting, { error, called, loading, data }] = useLazyQuery(
    GET_ALL_ISSUE_GROUPS,
    {
      fetchPolicy: 'no-cache',
    }
  );
  const [modalValue, setModalValue] = useState({});
  function handleEditClick(data) {
    setModalValue(data);
    setIsOpen(true);
  }
  React.useEffect(() => {
    loadGreeting();
  }, []);
  const setUpdatedData = (obj) => {
    toast({
      title: 'Update Success.',
      description: "Issue group is updated successfuly",
      status: 'success',
      duration: 5000,
      isClosable: true,
    })
    loadGreeting()
    setIsOpen(false);
  };
  if (error) return <p>Error : {error.message}</p>;
  return (
    <>
      
      <Modal
        onClose={() => {
          setIsOpen(false);
        }}
        isOpen={isOpen}
        size="full"
      >
        <AdminUpdateIssueGroupForm
          IssueGroupData={modalValue}
          setUpdatedData={setUpdatedData}
        />
      </Modal>
     {!loading && <TableContainer>
        <Table variant="simple">
          {/* <TableCaption>Imperial to metric conversion factors</TableCaption> */}
          <Thead>
            <Tr>
              <Th>Title</Th>
              <Th>Description</Th>
              <Th>Date</Th>
              <Th>Action</Th>
            </Tr>
          </Thead>
          <Tbody>
            {data &&
              data.IssueGroup.map((group) => (
                <Tr key={group.id}>
                  <Td>{group.title}</Td>
                  <Td>{group.description}</Td>
                  <Td>{group.createdAt}</Td>
                  <Td>
                    <Button
                      onClick={() => {
                        handleEditClick(group);
                      }}
                    >
                      {' '}
                      Edit{' '}
                    </Button>
                  </Td>
                </Tr>
              ))}
          </Tbody>
        </Table>
      </TableContainer>}
    </>
  );
}
Zulqarnain Jalil
  • 1,679
  • 16
  • 26
  • do you see an error with the way i have done that? – Mel Jan 04 '23 at 18:58
  • I was not able to execute the code you posted above but created the new one assuming the technique you are using in your application. I have posted the link to my project, you can check it online on stackblitz.com. – Zulqarnain Jalil Jan 05 '23 at 09:03