Answer the question
In order to leave comments, you need to log in
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;
};
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)}
Answer the question
In order to leave comments, you need to log in
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;
}
}
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 questionAsk a Question
731 491 924 answers to any question