Home > Net >  React Native/Redux State not updating after making API Call
React Native/Redux State not updating after making API Call

Time:02-10

I can return values from the Redux State, and when I make an API call, I see those being logged out but the state is not updating. I setup a basic App with a Redux Store to prove this out. And I've also include the Thunk library, which I read is needed for asynchronous State actions (like API). My guess is I am not returning the state properly at the end of the reducer, because again, if I log the values, there is detail being returned.

To consolidate the code as best as possible, I am only including the necessary pieces:

export default function App() {

  const OtherVal =  useSelector((state) => state.reducer2.WorkoutDetails);
  
  const dispatch = useDispatch();

  React.useEffect (() =>{
      dispatch({   type: 'Test_API' })
  })

  return (

   
<View style={styles.container}>
  <Text>Open up App.js to start rking on your app!</Text>
   
 <Text>Value is: {OtherVal}</Text>
  <StatusBar style="auto" />
</View>

  );
}

My Store:

import {createStore, applyMiddleware } from 'redux';
import rootReducer from './index';
import thunk from 'redux-thunk'

const store = createStore(rootReducer, applyMiddleware(thunk) );


export default store;

My Root Reducer (could be in the Store):

import { combineReducers } from 'redux'
import reducer2 from './FirstReducer'


export default combineReducers({
  reducer2,
})

My Reducer:

import axios from 'axios';

const initialState = {
    WorkoutDetails:null,
}

const reducer2 =  (state = initialState, action) => {

    if(action.type == 'Test_API'){
            axios.post('https://xxxx',{},
        {
            headers:{
            'X-Requested-With':'XMLHttpRequest'  
            , 'Content-Type': 'application/json',
            }  
        }
        ).then(function (response) {
            // handle success
            console.log('API Call 2')
            const val = JSON.parse(response.data.recordset[0].EndPoint)
            console.log('JSON Val', val)
            return {...state,WorkoutDetails: val}
        })
    }

    console.log('default Red',state) 
    return state     
}
export default reducer2;

CodePudding user response:

Try adding catch too

.then(function (response) {
            // handle success
            console.log('API Call 2')
            const val = JSON.parse(response.data.recordset[0].EndPoint)
            console.log('JSON Val', val)
            return {...state,WorkoutDetails: val}
        })
.catch(function (error) {
            // handle error
            console.log('API Call 2 error : 'error)
            return state
        })

CodePudding user response:

Instead of calling your API in reducer , you can call it in Action creator and then dispatch your action with payload as response. Based on the dispatch action type you can return your updated state to store through reducer.

Component dispatch an action -> apply your thunk (api call)->dispatch an action with API response data ->reducer update the store with correct state based on the action type.

Please refer the below URL: https://www.freecodecamp.org/news/redux-thunk-explained-with-examples/

  • Related