Home > Software design >  How to get data from an API using redux?
How to get data from an API using redux?

Time:06-10

I am requesting an API using redux and saga I the request is working fine I am able to get API returned data in the reducer, but I am not able to get that data in the home.js I am new to redux please help me.

in my home.js this is how I am making a call

const fetchSessionData = () => {
   dispatch(
      fetchSession({
        token: token
      })
    )
  }

action.js

export const fetchSession = data  => {
  return {
    type: Action.SESSION_DATA,
    payload: {data},
  };
};

this is reducer file

export const SessionData = (state = sessionState, action) => {
  console.log('inside session reducer', JSON.stringify(action));
  switch (action.type) {
    
    case Action.SESSION_FETCH_SUCCESS:
      
      return {
        ...state,
        isLoading: false,
      };
    case Action.SESSION_FETCH_ERROR:
      return {
        ...state,
        sagaerror: action.error,
        isLoading: false,
      };
    case Action.SESSION_DATA:
      return {
        ...state,
        isLoading: true,
      };
    
    default:
      return state;
  }
};

and this is the api

export function fetchSessionData(payload) {
  return fetch(`${url}/session/`, {
    method: 'GET',
    headers: {
      Authorization: `Bearer ${payload.token}`,
      Accept: 'application/json',
      'Content-Type': 'application/json',
    }
  })
    .then(response => response.json())
    .then(res => {
      return res;
    })
    .catch(error => {
      throw error;
    });
}

how can I get the returning data from api in home.js?

CodePudding user response:

Looks like you are not storing back the response from saga.

Please have an action for storing the response into your reducer.you may use

  yield put(storeactionname(payload received from api reponse);

in your saga method and in reducer your action.payload should be stored into a state variable

and in your component you can use useSelector like below

  const { yourvariableNameInStateInReducer } =
   useSelector((state) => state.yourreducername);

CodePudding user response:

As you say you will able to get data to reducer. It's then fine in that section. In the component you need to select stored data from the store. If you are using functional component you can use useSelector hook in react-redux. If you are using class component then you need to use connect function, you need to pass mapStateToProps and mapDispatchToProps arguments to the connect function. Refer https://react-redux.js.org/api/connect

  • Related