Search code examples
react-nativereduxreact-reduxredux-thunkredux-toolkit

How to Get createAsyncThunk In The Correct Way Data React Native


I am a new in react native Redux Newest Documentation. I want to use createAsyncThunk to get my api data using Axios.

Below my code :

App.js

import React, { useState } from 'react';
import { Provider } from 'react-redux';
import { configureStore } from '@reduxjs/toolkit';
import ApiChartingSlice from './redux/slice/api/ApiChartingSlice';
import LoginNavigator from './navigation/LoginNavigator';



const store = configureStore({
  reducer: {    
    ApiChartingMenu: ApiChartingSlice
  }
});


export default function App() {
  return (        
    <Provider store={store}>
      <LoginNavigator />
    </Provider>
  );

}

ApiChartingAxios.js

import axios from "axios";
import { BasicAuthUsername, BasicAuthPassword } from "../utility/utility";
    
export default axios.create({
    baseURL: 'https://blablabla.id/index.php',
    headers: {
        auth: {
            username: BasicAuthUsername,
            password: BasicAuthPassword
          }
    }
});

SubApiChartingAxios.js

import ApiChartingAxios from "../ApiChartingAxios";
    
export const SubApiChartingMenu = async () => {
    const response = await ApiChartingAxios.get('/ApiChartingMenu',{
        params: null
    });          
            
    return response;
};

ApiChartingSlice.js

import { createAsyncThunk, createSlice } from '@reduxjs/toolkit'
import { SubApiChartingMenu } from '../../../api/subapi/SubApiChartingAxios';


export const ApiChartingMenuThunk = createAsyncThunk(
    'ApiChartingMenu',
    async () => {
        const response = await SubApiChartingMenu();
        console.log(response);
        return response.data.Data;        
    } 
)
  
  
// status: 'idle' | 'loading' | 'succeeded' | 'failed',
const ApiChartingMenuSlice = createSlice({
    name: 'ApiChartingMenu',
    initialState: {
        apiData: {},
        status: 'idle',
        error: null
    },
    reducers: {},
    extraReducers: {
        [ApiChartingMenuThunk.pending.type]: (state, action) => {
            state.playerList = {
                status: "loading",
                apiData: {},
                error: {},
            };
        },
        [ApiChartingMenuThunk.fulfilled.type]: (state, action) => {
            state.playerList = {
                status: "idle",
                apiData: action.payload,
                error: {},
            };
        },
        [ApiChartingMenuThunk.rejected.type]: (state, action) => {
            state.playerList = {
                status: "idle",
                apiData: {},
                error: action.payload,
            };
        },
    }
});


export default ApiChartingMenuSlice.reducer;

And the last is my screen output:

ChartScreen.js

import { useNavigation } from '@react-navigation/native';
import React, { useEffect, useState, useCallback } from 'react';
import { View, Text, StyleSheet, TouchableOpacity, KeyboardAvoidingView, TextInput, Button } from 'react-native';
import { useDispatch, useSelector } from 'react-redux';
import { ApiChartingMenuSlice, ApiChartingMenuThunk } from '../../redux/slice/api/ApiChartingSlice';


const ChartScreen = () => { 
    console.log('ChartScreen');    
    const dispatch = useDispatch();
    console.log(dispatch(ApiChartingMenuThunk()));    
    
    const chartData = useSelector(state => state.ApiChartingMenu.apiData);    
    console.log(chartData);
    

    return (        
        <View>
            <Button title="test" onPress={() => {}} />
        <ChartComponent />
        </View>
    );
};


export default ChartScreen;

Problem: I don't know why in my ChartScreen.js this line : console.log(dispatch(ApiChartingMenuThunk()));

return :

Promise {
  "_U": 0,
  "_V": 0,
  "_W": null,
  "_X": null,
  "abort": [Function abort],
  "arg": undefined,
  "requestId": "oqhkA7eyL_VV_ea4FDxr3",
  "unwrap": [Function unwrap],
}

But in ApiChartingSlice.js in this line console.log(response);

return the correct value.

So, what is the correct way to retrive the value from the createAsyncThunk from my ChartScreen.js

The Api content is a list menu.

I want when first open the apps It execute the redux and show all my list menu.

But now just try to console.log the ApiChartingMenuThunk in ApiChartingSlice.js is not working.

Can anybody solve and guide me to a solution ? Thank You


Solution

  • I figured it out myself the problem is on this file : ApiChartingSlice.js

    and this line should be :

    [ApiChartingMenuThunk.fulfilled.type]: (state, action) => {
                state.playerList = {
                    status: "idle",                
                    apiData: state.apiData.push(action.payload),
                    error: {},
                };
    

    also you need to dispatch using this code :

    in file ChartScreen.js

    this is how we dispatch it.

    const toggleGetMenuHandler = useCallback(() => {        
            dispatch(ApiChartingMenuThunk())
            .unwrap()
            .then((originalPromiseResult) => {        
                // console.log(originalPromiseResult);        
            })
            .catch((rejectedValueOrSerializedError) => {        
                console.log(rejectedValueOrSerializedError);        
            })
        }, [dispatch]);    
    
    
        useEffect(() => {
          toggleGetMenuHandler();                
        }, [toggleGetMenuHandler]);
            },
    

    Now this code : const chartData = useSelector(state => state.ApiChartingMenu.apiData);
    will have a correct data.