Я не могу получить свои данные из базы данных MongoAtlas. Мой сервер настроен правильно, так как у меня есть данные, когда я получаю http://localhost: 5000 / api / v1 / recipes Поэтому я создал два файла: GlobalState и AppReducer:
import AppReducer from "./AppReducer";
import axios from "axios";
// Initial state
const initialState = {
recipes: [],
error: null,
loading: true,
}
// Create context
export const GlobalContext = createContext(initialState);
// Provider component
export const GlobalProvider = ({ children }) => {
const [state, dispatch] = useReducer(AppReducer, initialState);
// Actions
async function getRecipes() {
try {
const res = await axios.get('/api/v1/recipes');
console.log(res);
dispatch({
type: 'GET_RECIPES',
payload: res.data.data
});
} catch (err) {
dispatch({
type: 'RECIPE_ERROR',
payload: err.response.data.error
});
}
}
return (
<GlobalContext.Provider
value={{
recipes: state.recipes,
error: state.error,
loading: state.loading,
getRecipes
}}
>
{children}
</GlobalContext.Provider>
);
};
export default (state, action) => {
switch (action.type) {
case "GET_RECIPES":
return {
...state,
loading: false,
recipes: action.payload
};
case "RECIPE_ERROR":
return {
...state,
error: action.payload
};
default:
return state;
}
}
Сначала я пытаюсь восстановить эти данные и отобразить их в одном из моих компонентов:
import React, { useContext, useEffect } from "react";
import { GlobalContext } from "../context/GlobalState";
export const MyRecipes = () => {
const { recipes, getRecipes } = useContext(GlobalContext);
useEffect(() => {
getRecipes();
// eslint-disable-next-line react-hooks/exhaustive-deps
}, []);
console.log(recipes);
return(
<>
<h1>Mes Recettes</h1>
<ul>
{recipes.map(recipe=> (<li key={recipe.id} recipe={recipe}/>))}
</ul>
</>
)
}
Как и у меня ошибка × TypeError: getRecipes не является функцией. И console.log рецептов пуст
Я поставил в пакет прокси. json
{
"name": "qu-est-ce-qu-on-mange",
"version": "0.1.0",
"private": true,
"dependencies": {
"@testing-library/jest-dom": "^4.2.4",
"@testing-library/react": "^9.3.2",
"@testing-library/user-event": "^7.1.2",
"axios": "^0.19.2",
"react": "^16.12.0",
"react-dom": "^16.12.0",
"react-icons": "^3.9.0",
"react-router-dom": "^5.1.2",
"react-scripts": "3.4.0"
},
"scripts": {
"start": "react-scripts start",
"build": "react-scripts build",
"test": "react-scripts test",
"eject": "react-scripts eject"
},
"eslintConfig": {
"extends": "react-app"
},
"browserslist": {
"production": [
">0.2%",
"not dead",
"not op_mini all"
],
"development": [
"last 1 chrome version",
"last 1 firefox version",
"last 1 safari version"
]
},
"proxy": "http://localhost:5000"
}