0
const initialState = {
  data: []
}

function reducer (state, action) {
    switch(action.type) {
        case 'case':
            return (
                axios.get('/api').then(
                    // res => console.log(res)
                    // res => console.log(res.data)
                    res => ({ data: res.data })
                )
            )
        default:
            return state    
    }
}


export default function Component() {
    const [state, dispatch] = useReducer(reducer, initialState)
 
    console.log(state)
    console.log(state.data)

    return (
        <button onClick={() => dispatch({ type: 'case' })}>button</button>
    )
}

In my code, what is my mistake? I get Promise {<pending>} and undefined after two line of console.log inside the Component. It seems state is not being updated before printing state on console. How to fix that?

Rishad
  • 141
  • 2
  • 9
  • In that case, I probably do not need to use useReducer anymore. I wanted to leverage this hook as I have 3 cases for 3 different api endpoints. Instead, I will then go back for useState if I had to define functions for onClick handler. Right? @RobinZigmond – Rishad Aug 03 '21 at 18:53
  • oh sorry, I totally misread - my fault. I had been blinded by "reducer" and thought you were using Redux - but of course you're not, you're using plain React and the `useReducer` hook. In that case my links above are meaningless, although the first part stands - you can't directly do what you're doing, but can make asynchronous requests in the event handler and dispatch based on the result. Sorry again. – Robin Zigmond Aug 03 '21 at 18:59
  • Does this answer your question? [React useReducer async data fetch](https://stackoverflow.com/questions/53146795/react-usereducer-async-data-fetch) – Robin Zigmond Aug 03 '21 at 19:01
  • I think the above question covers this area quite well. I note some of the answers also talk about Redux middleware like thunk etc, as I did - but you can't directly use those with useReducer without writing quite a bit of additional "infrastructure" yourself. Basically useReducer is only designed for simple, synchronous, use-cases I think. – Robin Zigmond Aug 03 '21 at 19:02
  • You are not supposed to say sorry man! It's fine. Now, trying the above solutions... – Rishad Aug 03 '21 at 19:06
  • @RobinZigmond I could not fix the issue yet. The link you provided above doesn't clear everything understandable. Still arise confusions on async operation inside reducer function, as I want to handle api request after dispatch is called and expecting for state update before jsx returns. Better I will get rid off using `useReducer` hook? If this lacks of flexibility ... – Rishad Aug 04 '21 at 05:15

0 Answers0