При формировании массива полученных с сервера объектов падает ошибка
Я отправил на сервер запрос профиля people[index] и получил объект. В этом объекте есть массив films с api-шками (ссылками) на фильмы. Я получил этот массив и через for each отправил эти api на сервер. В процессе формируется нужный мне массив фильмов(объектов), но при добавлении последнего объекта падает ошибка: Unhandled Rejection (TypeError): state.films.push is not a function or its return value is not iterable. Надеюсь, объяснил понятно, код прилагается)
/////////api
export const profileAPI = {
getProfile(id) {
return axios.get(`https://swapi.dev/api/people/${id}`);
},
getFilm(api) {
return axios.get(api);
},
};
/////////reducer
let initialState = {
profileData: null,
films: [],
};
const profileReducer = (state = initialState, action) => {
switch (action.type) {
case SET_PROFILE:
return {
...state,
profileData: action.profile,
};
case SET_FILM:
return {
...state,
films: [...state.films.push(action.film)], //зыесь падает ошибка
};
default:
return state;
}
};
//action-creators
export const setProfile = (profile) => ({ type: SET_PROFILE, profile });
export const setFilm = (film) => ({ type: SET_FILM, film });
//Tunk-creators
export const getProfile = (id) => {
return (dispatch) => {
profileAPI.getProfile(id).then((response) => {
dispatch(setProfile(response.data));
});
};
};
export const getFilm = (api) => {
return (dispatch) => {
debugger;
profileAPI.getFilm(api).then((response) => {
dispatch(setFilm(response.data));
});
};
};
export default profileReducer;
////////component
class Profile extends React.Component {
componentDidMount() {
if (this.props.profileData) {
this.props.profileData.films.forEach((item) => { //здесь я перебираю массив ссылок на фильмы
this.props.getFilm(item); //а здесь отправляю ссылки на сервер
});
}
}
componentDidUpdate(prevProps) {
if (prevProps.profileData !== this.props.profileData) {
if (this.props.profileData) {
let films = this.props.profileData.films;
films.forEach((item) => { //здесь я перебираю массив ссылок на фильмы
this.props.getFilm(item); //а здесь отправляю ссылки на сервер
});
}
}
}
render() {
if (!profileData) {
return <div>Loading...</div>;
}
return (
<div className={s.person}>
//реализация UI
</div>
);
}
}
export default Profile;
Ответы (1 шт):
Автор решения: viktor-gif
→ Ссылка
Мне дали ответ на мой вопрос. Нужно [...state.films.push(action.film)] поменять на state.films.concat(action.film).