Im calling function inside useEffect hook like this:
useEffect(() => {
const getFirstLevelCategoryData = async (e) => {
const config = {
headers: {
'Content-Type': 'application/json',
Authorization: `Bearer ${userInfo.token}`,
},
};
const { data } = await axios.get('/api/category/firstlevel', config);
return data;
};
console.log(getFirstLevelCategoryData());
});
Promise { : "pending" }
: "fulfilled"
: Array(29) [ "Audio", "Automobiles", "Baby & Kids Fashion", … ]
I am using similar code in other place also which is working fine but this one keep giving pending state. Called the API from postman, working fine. Any ideas? Please help.
Im expecting an JSON string, but its in pending state.
UPDATED
//Declaration of variable:
const [mainCategory, setMainCategory] = useState([]);
// Function outside of useEffect hook to prevent it calling from over and over again
const getFirstLevelCategoryData = async (e) => {
const config = {
headers: {
"Content-Type": "application/json",
Authorization: `Bearer ${userInfo.token}`,
},
};
const { data } = await axios.get("/api/category/firstlevel", config);
setMainCategory(data);
};
if (mainCategory.length === 0) getFirstLevelCategoryData();
//Using it inside <Typeahead/> element in JSX:
<Typeahead
id="basic-typeahead-single"
labelKey="category"
onChange={(e) => setMainCategory(e.target.value)}
options={mainCategory}
placeholder="Choose a state..."
selected=""
/>
3
Answers
Basically you are returning a promise from your function so to get the values in a way you’re expecting you need to do something like this:
const result = await getFirstLevelCategoryData()
console.log("result", result)
The REQUEST is working fine the issue is that this line :
Is executed before the function returning data, try :
And you will see your
data
outputed afterconsole.log(getFirstLevelCategoryData());
So what you have to do is to use
data
directly inside the function there is no need to return itThis is because you don’t
await
(or.then
)getFirstLevelCategoryData()
, so it actually returns an unresolved promise.You could use it like this (.then):
Or like this (await):
Here’s also a codesandbox link: https://codesandbox.io/s/quiet-river-11y75n