Access to API using Redux

I have a react-redux app. I need to call API and used it in my component. The app is called with fetch in function in utills. All functions are group and export like this:

export const sportTeam = {
  getBasketballTeam,
  getBasketballTeamById,
}
function   getBasketballTeam() {
   let token = store.getState().UserReducer.token;
fetch(
    actions.GET_BASKETBALLTEAM,
{
      method: "GET",
      headers: { Authorization: `Bearer ${token}` },
    }
  )
    .then((res) => {
      if (res.status == 200 ) {
        return res.json();
      }
    })
    .then((response) => {
      console.log(response);
    })
    .catch((err) => {
      console.log(err);
    });
}

getBasketballTeam contains an array of objects. How can I get getBasketballTeam and used it in the component in the view to returning the list with this data?

If I understand you, then (assuming you are not using redux middleware like thunk or saga) then you can keep that value in state. The problem is that you’ve extracted this into a function (which can be a good thing). So now, you will have to pass in a callback to set the state in the calling component. So, back in the component you need to have the state start out at something (like null), that your UI can handle, but then this will update it with the new data.

About redux middleware there is using this and implemented in index in Provider:

import {createStore, applyMiddleware} from "redux";

import thunkMiddleware from "redux-thunk";

import rootReducer from "./redux-reducers";

export const store = createStore (rootReducer, applyMiddleware (thunkMiddleware));

also I try to implement in my view component and there is a result like this

dispatch => {
   debugger;
   return {
     sportTeam: () => dispatch (_utills_apiRequests_apiCalls__WEBPACK_IMPORTED_MODULE_16 __ ["sportTeam"]. getBasketballTeam ())
   };

`}`

Could you suggest to me how to get in view correctly and display the data in the list?

If you have thunk already, you can just set off the redux action in your component, then it will update your redux state when it can. Then your UI component will just need to be able to handle the initial data state as well as the populated data state. Presumably it should also be able to handle an error state.

This topic was automatically closed 182 days after the last reply. New replies are no longer allowed.