Код: Выделить всё
Warning: RangeError: Maximum call stack size exceededВот вызов:
Код: Выделить всё
useEffect(() => {
if (products.length === 0) {
console.log('[HomeScreen] Dispatching fetchProducts...');
dispatch(fetchSomeData());
}
}, [dispatch, products.length]);
< /code>
И вот метод Fetch: < /p>
export const fetchProducts = () => {
return async dispatch => {
console.log('[fetchProducts] Dispatching FETCH_PRODUCTS_REQUEST');
dispatch({type: 'FETCH_PRODUCTS_REQUEST'});
try {
console.log('[fetchProducts] Fetching data from API...');
const response = await fetch('https://fakestoreapi.com/products');
const data = await response.json();
console.log('[fetchProducts] API Response:', data.length, 'items');
dispatch({type: 'FETCH_PRODUCTS_SUCCESS', payload: data});
} catch (error) {
console.error('[fetchProducts] Error fetching products:', error);
dispatch({type: 'FETCH_PRODUCTS_FAILURE', error});
}
};
};
< /code>
А вот Reducer: < /p>
const productReducer = (state = initialState, action) => {
switch (action.type) {
case FETCH_PRODUCTS_REQUEST:
return {...state, loading: true};
case FETCH_PRODUCTS_SUCCESS:
return {...state, loading: false, products: action.payload};
case FETCH_PRODUCTS_FAILURE:
return {...state, loading: false, error: action.error};
default:
return state;
}
};
Код: Выделить всё
const client = axios.create({
baseURL: 'https://fakestoreapi.com/',
timeout: 10000,
headers: {
'Content-Type': 'application/json',
},
});
export const fetchSomeData = (dispatch, getState) => {
console.log('Fetching data from API...');
try {
client.get('products').then(data => {
console.log('Number of todos before loading: ', getState().data.length);
// Dispatch an action with the todos we received
dispatch({type: 'FETCH_PRODUCTS_SUCCESS', payload: data});
// Check the updated store state after dispatching
const allTodos = getState().data;
console.log('Number of todos after loading: ', allTodos.length);
});
} catch (error) {
console.error('Error fetching data:', error);
}
};
Подробнее здесь: https://stackoverflow.com/questions/795 ... g-api-data