Как правильно получить данные с сервера в initial state React Redux?
При отрисовки приложения нужно получать данные с сервера и отрисовывать их. Не могу понять почему у меня state пустой.
app.js
import { useState, useEffect } from 'react';
import AddNoteButton from './components/add-note-button/add-note-button';
import AddNote from './components/add-note/add-note';
import NotesList from './components/notes-list/notes-list';
import TagsList from './components/tags-ist/tags-list';
import { useSelector } from 'react-redux';
const App = () => {
const state = useSelector((state) => state);
console.log(state);
const [ showAddNote, setShowAddNote ] = useState(false);
const [ tags, setTags ] = useState([]);
// Get all tags
const getAllTags = (notes) => {
const newTags = new Set();
notes.map((note) => {
return note.tags.forEach((it) => newTags.add(it));
});
return [ ...newTags ];
};
//Sort notes
const sortNotes = (checked, value) => {
setTags(!tags.includes(value) && checked ? [ ...tags, value ] : tags.filter((n) => n !== value));
};
const filteredNotes = state.filter((note) => {
return !tags.length || tags.find((item) => note.tags.includes(item));
});
return (
<div className="wrapper has-background-dark">
<div className="container is-fluid">
<div className="columns has-text-light">
<div className="wrapper-column column has-background-dark">
<AddNoteButton onAdd={() => setShowAddNote(!showAddNote)} isDisabled={showAddNote} />
<TagsList tags={getAllTags(state)} onSort={sortNotes} />
</div>
<div className="wrapper-column column has-background-dark is-three-quarters">
{showAddNote ? <AddNote onHide={() => setShowAddNote(false)} /> : ''}
<NotesList notes={filteredNotes} />
</div>
</div>
</div>
</div>
);
};
export default App;
index.js
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
import reportWebVitals from './reportWebVitals';
import { Provider } from 'react-redux';
import { store } from './state/store';
import { fetchNotes } from './state/action-creators';
store.dispatch(fetchNotes());
ReactDOM.render(
<React.StrictMode>
<Provider store={store}>
<App />
</Provider>
</React.StrictMode>,
document.getElementById('root')
);
// If you want to start measuring performance in your app, pass a function
// to log results (for example: reportWebVitals(console.log))
reportWebVitals();
store.js
import { createStore, applyMiddleware } from 'redux';
import reducers from './reducers/index';
import thunk from 'redux-thunk';
export const store = createStore(reducers, {}, applyMiddleware(thunk));
reducers
import { combineReducers } from 'redux';
import notesReducer from './notesReducer';
const reducers = combineReducers({
notes: notesReducer
});
export default reducers;
reducer
let initialState = [];
const reducer = (state = initialState, action) => {
switch (action.type) {
case 'loadNotes':
return [ ...state, action.payload ];
default:
return state;
}
};
export default reducer;
action creator
export const fetchNotes = () => {
return async (dispatch) => {
const res = await fetch('http://localhost:5000/notes');
const json = await res.json();
dispatch(loadNotes(json));
console.log(json);
};
};
export const loadNotes = (notes) => ({
type: 'loadNotes',
payload: notes
});
Ответы (1 шт):
Автор решения: p1uton
→ Ссылка
store.dispatch(fetchNotes()); нужно убрать из index.js
В app.js добавить
const dispatch = useDispatch();
useEffect(() => {
dispatch(fetchNotes());
}, []);
useDispatch нужно импортировать из react-redux
import { useDispatch } from 'react-redux'
Хук useEffect отработает один раз при монтировании компонента и загрузит данные с сервера.