skip to Main Content

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


  1. 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)

    Login or Signup to reply.
  2. The REQUEST is working fine the issue is that this line :

    console.log(getFirstLevelCategoryData());
    

    Is executed before the function returning data, try :

    const { data } = await axios.get('/api/category/firstlevel', config);
    console.log(data)
    );
    

    And you will see your data outputed after console.log(getFirstLevelCategoryData());

    So what you have to do is to use data directly inside the function there is no need to return it

    Login or Signup to reply.
  3. This is because you don’t await (or .then) getFirstLevelCategoryData(), so it actually returns an unresolved promise.

    You could use it like this (.then):

    const getFirstLevelCategoryData = async (e) => {
        const config = {
          headers: {
            "Content-Type": "application/json"
            // Authorization: `Bearer ${userInfo.token}`,
          }
        };
    
        const { data } = await axios.get(
          "https://jsonplaceholder.typicode.com/posts/1",
          config
        );
    
          return data
      }
    
      useEffect(() => {
        getFirstLevelCategoryData()
          .then(data => {
            console.log(data);
           })
      }, []);
    

    Or like this (await):

      const getFirstLevelCategoryData = async (e) => {
        const config = {
          headers: {
            "Content-Type": "application/json"
            // Authorization: `Bearer ${userInfo.token}`,
          }
        };
    
        const { data } = await axios.get(
          "https://jsonplaceholder.typicode.com/posts/1",
          config
        );
    
        // Log data here
        console.log(data)
      };
    
      useEffect(() => {
        getFirstLevelCategoryData();
      }, []);
    

    Here’s also a codesandbox link: https://codesandbox.io/s/quiet-river-11y75n

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search