Здравствуйте! Изучаю Redux и с толкнулся с одной проблемой. Делаю нечто вроде новостной ленты. Есть два стейта: со всеми новостями и с одной + комменты. Первый работает нормально, но со вторым есть проблемы. Когда нажимаешь на новость на главной странице, переходишь на страницу новости, на которой отправляется запрос на сервер для получения инфы и происходит рендер. Но почему-то рендер не ожидает получения ответа, а пытается сразу отрисовать, соответственно получаю undefined.
Код страницы
import React,{useEffect,useState, } from 'react';
import {useParams} from 'react-router-dom'
import { useTypedSelector } from '../hooks/useTypedSelector';
import NewView from '../component/NewView/newView';
import { dataType } from '../types/types';
import { useAppDispatch } from '../hooks/useAppDispatch';
import { fetchDataNew } from '../store/action-creators/newData';
const NewPage:React.FC = () =>{
let {id} = useParams<{id:string}>()
const dispatch = useAppDispatch()
const {data,error,loading} = useTypedSelector(state=>state.new)
useEffect(()=>{
dispatch(fetchDataNew(id))
}, [])
if (loading){
return(<h1>Загрузка</h1>)
}
if(error){
return(<h1>{error}</h1>)
}
/*return(
<NewView dataNew={data.new} comments={data.comments}/>
)*/
return(
<div className="container">
<h1>{data.new.id}</h1>
</div>
)
}
export default NewPage
acton-creators
import axios from "axios"
import { Dispatch } from "react"
import { DataActionNew, DataActionTypes, dataType } from "../../types/types"
export const fetchDataNew = (id:string) =>{
return async(dispatch: Dispatch<DataActionNew>)=>{
try {
dispatch({type:DataActionTypes.FETCH_DATA})
const url = `http://localhost:5000/api/new/${id}`
const response = await axios.get(url)
dispatch({type:DataActionTypes.FETCH_DATA_SUCCESS,payload:response.data})
} catch (error) {
return dispatch({
type:DataActionTypes.FETCH_DATA_ERROR,
payload:"Произошла ошибка загрузки данных"})
}
}
}
reducer
import { initialState,DataAction,DataState,DataActionTypes } from "../../types/types";
import { initialStateNew,DataActionNew,DataStateNew } from "../../types/types";
export const newsReducer = (state = initialState, action:DataAction): DataState =>{
switch (action.type){
case DataActionTypes.FETCH_DATA:
return {loading:true, error:null, data: []};
case DataActionTypes.FETCH_DATA_SUCCESS:
return {loading:false, error:null, data: action.payload};
case DataActionTypes.FETCH_DATA_ERROR:
return {loading:false, error:action.payload, data: []};
default:
return state
}
}
export const newReducer = (state = initialStateNew, action:DataActionNew): DataStateNew =>{
switch (action.type){
case DataActionTypes.FETCH_DATA:
return {loading:true, error:null, data: []};
case DataActionTypes.FETCH_DATA_SUCCESS:
return {loading:false, error:null, data: action.payload};
case DataActionTypes.FETCH_DATA_ERROR:
return {loading:false, error:action.payload, data: []};
default:
return state
}
}
index(reducer)
import { combineReducers } from "redux";
import { newsReducer, newReducer } from "./newsReducer";
export const rootReducer = combineReducers({
data: newsReducer,
new: newReducer
})
export type RootState = ReturnType<typeof rootReducer>
index
import { configureStore } from '@reduxjs/toolkit'
import {applyMiddleware, createStore} from 'redux'
import thunk from 'redux-thunk'
import { rootReducer } from './reducers'
import { newsReducer,newReducer } from './reducers/newsReducer'
export const store = configureStore({
reducer:{
data: newsReducer,
new: newReducer
}
})
export type RootState = ReturnType<typeof store.getState>
export type AppDispatch = typeof store.dispatch