M
M
mr jeery2018-02-01 17:15:25
JavaScript
mr jeery, 2018-02-01 17:15:25

How to properly load api in react?

I made an action on which data from the url will be loaded, but state.data returns an empty array through the action
reducer looks like this

const defaultState = {
  data: []
}


const API = () => {
  return  fetch( 'http://swapi.co/api/people/?format=json')
          .then( response => response.json() )


}

export const DataReducer = (state = defaultState, action) => {
  if (action.type === 'GET_DATA') {
    return { data: API() }
  }
    return state;
};

Checked fetch inside the component via console.log everything works.
componentDidMount() {
      fetch( 'https://api.coinmarketcap.com/v1/ticker/?limit=10%20')
        .then( response => response.json() )
        .then( (data) => this.setState({items:data}))
    }

  render() {
      return    {console.log(this.state.items)}

I ask you not to scold too much, I am at the beginning of training.

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
Anton Spirin, 2018-02-01
@jeerjmin

For asynchronous requests, you should use redux middleware like redux-thunk :

import { fetchInitialDataApi } from './api';

const FETCH_DATA_REQUEST = 'FETCH_DATA_REQUEST';
const FETCH_DATA_SUCCESS = 'FETCH_DATA_SUCCESS';
const FETCH_DATA_ERROR = 'FETCH_DATA_ERROR';

const fetchDataRequest = () => ({ type:  FETCH_DATA_REQUEST });

const fetchDataSuccess = data => ({
  type:  FETCH_DATA_SUCCES,
  payload: data,
});

const fetchDataError = error => ({
  type:  FETCH_DATA_ERROR,
  payload: error,
});

const fetchData => async dispatch => {
  try {
    dispatch(fetchDataRequest());
    const { data } = await fetchDataApi();
    dispatch(fetchDataSuccess(data));
  } catch error {
    dispatch(fetchDataError(error));
  }
};

const initialState = {
  data: {},
  isLoading: false,
  isError: false,
  error: null,
};

export default function(state = initialState, action) {
  const { type, payload } = action;

  switch (type) {
    case FETCH_DATA_REQUEST:
      return {
        ...state,
        isLoading: true,
        isError: false,
        error: null,
      };
    case FETCH__DATA_SUCCESS:
      return {
        ...state,
        data: payload,
        isLoading: false,
      };
    case FETCH_DATA_ERROR:
      return {
        ...state,
        isLoading: false,
        isError: true,
        error: payload,
      };
  default:
    return state;
  }
}

R
Roman Aleksandrovich, 2018-02-01
@RomReed

try like this

export const DataReducer = (state = defaultState, action) => {
  if (action.type === 'GET_DATA') {
    return { ...state, data: API() }
  }
    return state;
};

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question