I am trying to fetch some fruits using an API and displaying them into different components using axios. Problem is, it is not working. The data is not displaying. and I am not getting any records on the console. Please help. Here is what I have done, and I am using Context API for this one.
Fruits Data File
import React, { useState } from 'react';
import axios from 'axios';
import ApiContext from './ApiContext';
function FruitsData(props) {
const [fruits, setFruits] = useState([]);
const [selectedItem, setSelectedItem] = useState(null);
const fetchFruits = async () => {
const response = await axios.get('/api/fruits');
setFruits(response.fruits);
console.log(response.开发者_Python百科fruits)
}
const selectItem = (id) => {
const fruit = fruits.find(fruit => fruit.id === id);
setSelectedItem(fruit);
}
const fetchItem = async (id) => {
const response = await axios.get(`/api/fruit/${id}`);
setSelectedItem(response.fruit);
}
return (
<ApiContext.Provider value={[fruits, setFruits, selectedItem, selectItem, fetchFruits, fetchItem ]}>
{props.children}
</ApiContext.Provider>
);
}
export default FruitsData;
The Component to display the Fruits
import ApiContext from '../../contexts/ApiContext';
function Training() {
let navigate = useNavigate();
const [fruits, setFruits] = useContext(ApiContext);
return (
<div>
{fruits && fruits.map((fruit) => (
<FruitWidget fruit={fruit} key={fruit.id} />
))}
</div>
);
}
export default Training;
App.js
<FruitsData>
<Routes>
<Route path="training" element={<Training />} />
<Route path="fruit-details/:fruitId" element={<FruitDetails />} />
</Routes>
</FruitsData>
Kindly help, thank you
will be honest. did not read your code, you already said - have nothing on console it means your URL is not correct
const fetchFruits = async () => {
const response = await axios.get('/api/fruits'); // problem is here :)
setFruits(response.fruits);
console.log(response.fruits)
}
精彩评论