skip to Main Content

I have an axios.POST that I want to reuse in my code. the then part of my code will be different but when I add the POST part of the code to a function, I am getting the following error:

Uncaught TypeError: Cannot read properties of undefined (reading 'then')

My code:

const myFunc = (query, variables) => {
  axios.post(
    "https://test.com/graphql",
    {
      query: query,
      variables: variables,
    },
    {
      headers: headers,
    }
  );
};
myFunc(myQuery, {
  id: "12345",
  nm: "TEST",
}).then((res) => console.log(res.data.data));

Is there a way for me to reuse myFunc without getting an undefined error?

2

Answers


  1. you need to return in your post request

    const myFunc = (query, variables) => {
      return axios.post(
        "https://test.com/graphql",
        {
          query: query,
          variables: variables,
        },
        {
          headers: headers,
        }
      );
    };
    myFunc(myQuery, {
      id: "12345",
      nm: "TEST",
    }).then((res) => console.log(res.data.data));
    
    Login or Signup to reply.
  2. You need to return a Promise because an instance of a Promise will have the then() method which you want to call.

    The easiest way to do this is by just returning the Promise axios will be returning.

    const myFunc = (query, variables) => {
      return axios.post(
        "https://test.com/graphql",
        {
          query: query,
          variables: variables,
        },
        {
          headers: headers,
        }
      );
    };
    myFunc(myQuery, {
      id: "12345",
      nm: "TEST",
    }).then((res) => console.log(res.data.data));
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search