Search code examples
reactjsreact-hooksapollo-clientuse-effectuse-state

Reactjs useState hook not updating on promise data


I am using react hook instead of class based component but it is not updating the state when i fetch data from graphql API.

Here you go for my code:

import React, { useEffect, useState } from 'react';
import client from '../gqlClient';
import { gql, ApolloClient, InMemoryCache  } from '@apollo/client';


const client = new ApolloClient({
  uri: 'http://localhost:8000/graphql/',
  cache: new InMemoryCache(),
});


function EmpTable() {

  const [employee, setEmployee] = useState({});

    useEffect(() => {

        client
            .query({
                query: gql`
                query {
                  employees {
                    name
                  }
                }
                `
            })
            .then(result => {
              setEmployee({result});
              console.log(employee);
            });
    }, [])

    return (
        <div>return something</div>
    )
};


export default EmpTable;

When i print the employee It prints the initial value only.

But when print result, the console showing all the data that i have from API.

I made the useEffect only run once the page/component is loaded but it is not working.

Can anyone help me how to fix the issue?


Solution

  • There is another solution that you can use a custom hook to use your returned value in any component you want to use.

    import React, { useEffect, useState } from 'react';
    import client from '../gqlClient';
    import { gql, ApolloClient, InMemoryCache  } from '@apollo/client';
    
    
    const client = new ApolloClient({
      uri: 'http://localhost:8000/graphql/',
      cache: new InMemoryCache(),
    });
    
    const useCustomApi=()=>{
        const [employee, setEmployee] = useState({});
        useEffect(() => {
            client
                .query({
                    query: gql`
                    query {
                      employees {
                        name
                      }
                    }
                    `
                })
                .then(result => {
                  setEmployee({result});
                  
                });
        }, [])
    
    
    return employee;
    }
    
    function EmpTable() {
    
        const employee = useCustomApi();
        console.log(employee);
    
       return (
          <div>{JSON.stringify(employee,null,2)}</div>
       )
    };
    
    
    export default EmpTable;