'Why is Graphql data object only available outside the call function

I am new to graphql and react so I can't figure out why the loaded data return object is only available outside the mutation post which produced the data. Could someone please explain this concept?

The data object immediately after the call here always returns undefined for some reason:

const handleSubmit = async() => {
    try{  
      await addPerson({ variables: {  
        "name":Name,
        "title":Title,
        "imageURI":What } })
      ;
   
     console.log(data) // *** always undefined ***
     
    }

Somehow the data object is only available outside of the mutation query

export const SubmitPage = () => {
  const [addPerson, { data, loading, error }] = useMutation(Persons);
  const [addTask] = useMutation(Tasks);

  const [Name, setName] = useState<string>("");
  const [Title, setTitle] = useState<string>("");
  const [What, setWhat] = useState<string>("");

  
  
  if (loading) console.log("loading");
  if (error) console.log("error");
  
  console.log(data) // *** data only shows up here ***

  if (data === undefined){
    console.log("response data not loaded yet")
  }
  else{
    console.log(data.addPerson.id)

   
const handleSubmit = async() => {
    try{  
      await addPerson({ variables: {  
        "name":Name,
        "title":Title,
        "imageURI":What } })
      ;
   
     console.log(data) //always returns undefined
     
    }
    
    catch(e){console.log(e)}
  
  };

    
  return( <Container className = "submit-form">
          <Typography variant="h4">Submit Page</Typography>
          
        
          <Grid>
          First Name
          <TextField label = "required" value ={Name} onChange={e => setName(e.target.value)}/>
          Title
          <TextField label = "required" value ={Title} onChange={e => setTitle(e.target.value)}/>
          Some
          <TextField label = "required" value ={What} onChange={e => setWhat(e.target.value)}/>
          </Grid>
        
          <Button onClick ={handleSubmit} >submit</Button> 
          
          
          </Container>
)};


Solution 1:[1]

console.log(data) data is undefined inside the function because graphql loading from a database is an asynchronous operation. The data hasn't loaded when this line is executed.

Since this the useQuery / useMutation is a hook it will reload the function so the data will be there next render (thus seen outside the function)

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 dap