как записать результат fetch в state Redux
Нужна помощь в выполнении простой операции - запись результата fetch в store Redux. При маунте файла postlist.js данные из fetch запроса должны записываться в state, но ничего не происходит(даже action не стреляет в интсрументах разработчика. Заранее благодарю файл fetch.js
const BASE_URL = 'https://jsonplaceholder.typicode.com';
const fetchAllPosts = () => {
return fetch(`${BASE_URL}/posts`).then(response => {
return response.json();
});
};
файл operations.js
import { fetchAllPosts } from '../../fetch/fetch';
import actions from './actions';
export const fetchPosts = () => async dispatch => {
dispatch(actions.fetchPostRequest());
try {
const posts = await fetchAllPosts();
dispatch(actions.fetchPostSuccess(posts));
} catch (error) {
dispatch(actions.fetchPostError(error));
}
};
файл actions.js
import { createAction } from '@reduxjs/toolkit';
const fetchPostRequest = createAction('fetchPostRequest');
const fetchPostSuccess = createAction('fetchPostSuccess');
const fetchPostError = createAction('fetchPostError');
const filterItem = createAction('filter');
export default { filterItem, fetchPostRequest, fetchPostSuccess, fetchPostError };
файл store.js
import { configureStore } from '@reduxjs/toolkit';
import { combineReducers } from 'redux';
import { createReducer } from '@reduxjs/toolkit';
import actions from './actions';
const postReducer = createReducer([], {
[actions.fetchPostSuccess]: (_, action) => action.payload,
});
const error = createReducer(null, {
[actions.fetchPostError]: (_, action) => action.payload,
});
const filterReducer = createReducer('', {
[actions.filterItem]: (_state, action) => {
return action.payload;
},
});
const rootReducer = combineReducers({
posts: postReducer,
filteredPosts: filterReducer,
});
const store = configureStore({
reducer: rootReducer,
});
export default store;
файл postlist.js
import React from 'react';
import { useState, useEffect } from 'react';
import * as operations from '../redux/operations';
import { useDispatch} from 'react-redux';
export default function PostList() {
const dispatch = useDispatch();
useEffect(() => {
operations.fetchPosts();
}, [dispatch]);
return (
<div>
</div>
);
}
Ответы (1 шт):
Автор решения: Рустам Асланов
→ Ссылка
нашел проблему - вызов useEffect был написан с ошибкой. Корректная подпись:
useEffect(() => {
dispatch(operations.fetchPosts());
}, [dispatch]);