0

Convert Promise to data I am trying to convert my use state to use reducer. an async function is calling to fetch data and I'm not abale to use it in the reducer here is part of the code:

 switch (action.type) {
      case "load":
        
        const data = loadTodos()
        state = { ...state, todos: [...data] };
        return state;
}}





async function loadTodos() {
    return await todoService.getTodo();
    
  }

I tried to solve the problem in this way :

var myState = []
loadTodos().then((data) => {
          myState = [...data];
        });
        console.log(myState);

` myState is correct inside .then scope but outside is empty array.

Amir Esf
  • 1
  • 1
  • *"myState is correct inside .then scope but outside is empty array"*: that "outside" is happening **before** the promise has resolved. That is the whole idea of asynchronous execution: you need to put dependent code in the `then` callback, or after an `await`. `const data = loadTodos()` is assigning a promise to `data`... you need to continue the asynchronous pattern and use `await` or `then` here. – trincot Dec 28 '22 at 07:37
  • @trincot would you please write the required code to access data not promise in this case? I need the data to set in state , I cant use await there and with using then again its problematic – Amir Esf Dec 31 '22 at 07:19

0 Answers0