Home > Software design >  Return Promise { "_U": 0, "_V": 0, "_W": null, "_X": null, }
Return Promise { "_U": 0, "_V": 0, "_W": null, "_X": null, }

Time:03-09

This is my code in using REDUX :

ApiChartingReducer.js

    const ApiChartingMenuInitial = {
        apiData: []
    };
    
    export const ApiChartingMenuReducer = (state = ApiChartingMenuInitial, action) => {      
        switch (action.type) {
            case GET_MENU_CHART:                    
                 const getData = async () => {                             
                    try {
                        const response = await ApiChartingAxios.get('/ApiChartingMenu',{
                            params: null
                        });          
                        console.log(response.data.Data) // Data Exists
                        return response.data.Data;
                    } catch (error) {
                        console.log(error);
                    }                
                    return response.data.Data;                
                };    
                            
                console.log(getData());  // data not exists            
                // return {...state, apiData: getData()}
                
            default: 
                return state;
        }    
    };

In this line :

console.log(response.data.Data) // Data Exists

But in this line :

console.log(getData()); // Data not exists

and return :

    Promise {
      "_U": 0,
      "_V": 0,
      "_W": null,
      "_X": null,
    }

I cannot use useState in my redux reducer file. So How I can get my response data in getData() ?

CodePudding user response:

In a Redux reducer, you are not allowed to execute any asynchronous code.

A Redux reducer has to be a pure function without side effects.

Usually in Redux, you would do the fetching either outside of Redux or in a middleware like a thunk, and then dispatch an action with the data that was loaded, which will then be handled in the reducer.

Generally: you are writing a very outdated style of Redux here. Since 2019, the recommended style of Redux does not use switch..case reducers, ACTION_TYPES, immutable reducer logic, createStore or connect/mapStateToProps. You are very likely following outdated documentation. The new style is only 1/4 of the code and a lot less error-prone.

I would recommend you to follow the official Redux "Essentials" tutorial, which will teach you the new style and also goes over different methods of data fetching in the chapters 5, 7 and 8.

If you insist that you want to continue learning this old style of Redux, you can also look into the Redux Fundamentals tutorial, which shows the old style to explain some of the internals of Redux for those who are interested in that. Chapter 6 is all about data fetching.

  • Related