I'm trying to store data with my setState method inside my function but it never update it, however if I set them to a variable (I call it "x") it works.
I have my function which returns a Promise
I hope I can get help figuring out where I went wrong or understand if it cannot be done or not.
import { NextPage } from "next";
import { useState } from "react";
import { useAirtable } from "../functions/useAirtable";
import { MyType } from "../model/MyType";
const Foo: NextPage = () => {
const [barbaz, setBarbaz] = useState<any>([]);
let x: any = [];
try {
useAirtable("My_Table").then((data: MyType) => {
setBarbaz(data);
x = data;
console.log("print1: ", data); //It PRINTS data
console.log("print2: ", barbaz); //It PRINTS empty array
console.log("print3: ", x); //It PRINTS data
}
);
} catch (error) {}
console.log("print4: ", barbaz); //It PRINTS empty array
console.log("print5: ", x); //It PRINTS empty array
return <div> where is waldo </div>;
};
export default Foo;
Wrap your async call on a useEffect hook.
import { NextPage } from "next";
import { useState, useEffect } from "react";
import { useAirtable } from "../functions/useAirtable";
import { MyType } from "../model/MyType";
const Foo: NextPage = () => {
const [barbaz, setBarbaz] = useState<any>([]);
useEffect(() => {
useAirtable("My_Table").then((data: MyType) => {
setBarbaz(data);
}
}, [])
return <div> where is waldo </div>;
};
export default Foo;