Можно сделать примерно так:
import React from "react";
import thunk from "redux-thunk";
import { createStore, applyMiddleware } from "redux";
import { Provider } from "react-redux";
import SubComponent from "./SubComponent";
const initialState = {
items: [],
};
export const fetchItems = () => async (dispatch) => {
try {
dispatch(loadingAction());
const asyncData = await new Promise((resolve, reject) => {
setTimeout(() => {
if (Math.random() > 0.3) {
resolve(["abc", "def", "ghi"]);
} else {
reject(["error happend"]);
}
}, 1000);
});
dispatch(successAction(asyncData));
} catch (error) {
dispatch(errorAction(error));
}
};
const loadingAction = () => ({ type: "LOADING" });
const successAction = (data) => ({ type: "SUCCESS", payload: data });
const errorAction = (error) => ({ type: "ERROR", payload: error });
const reducer = (state = initialState, action) => {
switch (action.type) {
case "LOADING":
return { ...state, items: ["loading..."] };
case "SUCCESS":
return { ...state, items: action.payload };
case "ERROR":
return { ...state, items: action.payload };
default:
return state;
}
};
const store = createStore(reducer, applyMiddleware(thunk));
const Redux = () => {
return (
<Provider store={store}>
<h1>Redux</h1>
<SubComponent />
</Provider>
);
};
export default Redux;
SubComponent.js:
import React, { useEffect } from "react";
import { useSelector, useDispatch } from "react-redux";
import { fetchItems } from "./Redux";
const SubComponent = () => {
const items = useSelector((state) => state.items);
const dispatch = useDispatch();
useEffect(() => {
dispatch(fetchItems());
}, []);
return (
<div>
<h3>SubComponent</h3>
{items.map((item) => (
<div key={item}>{item}</div>
))}
</div>
);
};
export default SubComponent;
вот в этом коде:
export const makeApi = (apiKey) => () => {
const api = new Api(apiKey)
return {
type: SET_PROP,
payload: { field: 'API', value: api },
}
}
должна быть прописана асинхронная логика:
export const fetchApi = (apiKey) => async (dispatch) => {
try {
// установить состояние загрузки (dispatch loading action)
// получить данные с сервера
// dispatch success action
} catch {
// если произошла ошибка dispatch error action
}
}