Home > Software design >  Accessing promise result using async await and axios get
Accessing promise result using async await and axios get

Time:08-04

I am calling a function in my reducer which returns a promise and I want to assign the promise result of it to an existing initialState field from my reducer. I'm not sure how to do this though. I've tried some solutions I saw online but it doesn't seem to work.

Edit: I am able to print out my promise result but I get an error: Uncaught TypeError: Cannot read properties of undefined (reading 'idType'). I have a line in my code which is causing the error but I'm not sure how to fix it:

const idType = useSelector((state) => state.questionnaireData.tmpParams.idType)

My function:

const getId = async (idType) => {
try {
  const result = await axios.get(`https://www.exampleurl.com/${idType}`)
  return res.data[0]["idtype"];
} catch (err) {
  console.error("idType", err.toJSON());
}

My initial state and reducer:

const initialState = {
  tmpParams: {
    idType: ""
  }
}

setTmpParams: async (state, action) => {
  const { idtype } = action.payload;
  const tmpParams = {};

  tmpParams.idType = await getId(idtype);
  console.log(tmpParams.idType) // prints a promise object

  return {
    ...state,
    tmpParams: {
      ...state.tmpParams,
      ...tmpParams,
    },
  };
}

My promise object:

Promise {<pending>}
  [[Prototype]]: Promise
  [[PromiseState]]: "fulfilled"
  [[PromiseResult]]: "Visual"

CodePudding user response:

setTmpParams: async (state, action) => {
  tmpParams.idType = await getId(idtype);
  console.log(tmpParams.idType) // prints a promise object

  return {
    ...state,
    tmpParams: {
      ...state.tmpParams,
      ...tmpParams,
    },
  };
}

CodePudding user response:

getId is an asynchronous function, so it will return a promise. Therefore the reducer doesn't wait for getId to resolve before continuing execution. A potential solution would be to make your reducer an async function and await getId.

CodePudding user response:

Your problem seems to be that you're calling an async method from a reducer and this is an anti-pattern, since reducers by themselves should not have side effects. Since you're printing the result of your getById function, the result is effectively a promise.

You should refactor your application in a way that allows you to handle side effects properly. One way could be using Redux Thunk or handling the side effects in your component and passing the results into your reducer.

  • Related