React useContext – wait for api to finish

const tableContext = React.createContext();
const tableContextProvider = ({children}) => {
   const [isTableOne, setTableOne] = useState(false);
   const [isTableTwo, setTableTwo] = useState(false);

   useEffect(() => {
       setTableValues();
   }, []);

   function setTableValue() {
       // api call returns result
       setTableOne(result.IS_TABLE_ONE); // true
       setTableTwo(result.IS_TABLE_TWO); // false
   }

   return (<TableContext.Provider value={{isTableOne, isTableTwo}}>{children}</TableContext.Provider>);
};

In a different component, the result shows:

{isTableOne:false, isTableTwo:false}
{isTableOne:true, isTableTwo:false}

It returns two objects and it takes some time to return the second one. How could I make it wait and only return the last result?

2 thoughts on “React useContext – wait for api to finish”

  1. Assuming your request is being made inside that useEffect, here’s how you can do it:

    useEffect(() => {
        async init(){
          const response = await myApiCall(); // Wait for response with a promise
          setTableValues(); // Only call the setter after you get the values
        }
        init();
    
    },[]);
    
    Reply

Leave a Comment