@Grione

Как получить state через fetch?

Подскажите, где ошибка? Никак не могу корректно получить данные с сервера.
Использую json server npm. Сейчас у меня в state приходит [object Object],[object Object],[object Object], и соответственно всё падает. При этом после фетча консоль показывает корректный массив.
Файл json выглядит вот так :
{
  "notes": [
    {
      "id": 1,
      "title": "First note",
      "text": "first text",
      "tags": [ "movies", "books", "thoughts" ],
      "editing": false
    },
    {
      "id": 2,
      "title": "Second note",
      "text": "Second text",
      "tags": [ "goals" ],
      "editing": false
    },
    {
      "id": 3,
      "title": "Third note",
      "text": "Another one text",
      "tags": [ "goals", "soccer", "poker" ],
      "editing": false
    }
  ]
}


//action creators 
export const fetchNotes = () => {
	return async (dispatch) => {
		fetch('http://localhost:5000/notes/').then((res) => res.json()).then((json) => {
			console.log(json); // вот здесь нормальный массив
			dispatch({
        type:'loadNotes',
        payload: json
      });
		});
	};
};

// reducers
let initialState = [];

const reducer = (state = initialState, action) => {
	switch (action.type) {
		case 'loadNotes':
			return [ ...state, action.payload ];

		default:
			return state;
	}
};

export default reducer;

// store
export const store = createStore(reducers, {}, applyMiddleware(thunk));

//index.js
ReactDOM.render(
	<React.StrictMode>
		<Provider store={store}>
			<App />
		</Provider>
	</React.StrictMode>,
	document.getElementById('root')
);

//app.js
const App = () => {
	const state = useSelector((state) => state.notes);

	const dispatch = useDispatch();

	useEffect(() => {
		dispatch(fetchNotes());
	}, []);

  console.log(`state: ${state}`);

	const [ showAddNote, setShowAddNote ] = useState(false);
	const [ tags, setTags ] = useState([]);

	// Get all tags
	const getAllTags = (notes) => {
		const newTags = new Set();

		if (notes.length) {
      console.log(`notes: ${notes}`)
			notes.map((it) => {
				console.log(`it: ${it}`); // А тут и далее [object Object],[object Object],[object Object]
				return it.tags.forEach((it) => newTags.add(it));
			});
		}

		return [ ...newTags ];
	};

	const filteredNotes = state.filter((note) => {
		return !tags.length || tags.find((item) => note.tags.includes(item));
	});

	//Sort notes
	const sortNotes = (checked, value) => {
		setTags(!tags.includes(value) && checked ? [ ...tags, value ] : tags.filter((n) => n !== value));
	};

	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;


Падает же всё вот так
6163f46183f61674347715.jpeg
  • Вопрос задан
  • 68 просмотров
Решения вопроса 1
alexey-m-ukolov
@alexey-m-ukolov Куратор тега React
case 'loadNotes':
  return [ ...state, ...action.payload ];
Ответ написан
Пригласить эксперта
Ваш ответ на вопрос

Войдите, чтобы написать ответ

Войти через центр авторизации
Похожие вопросы