I am new to react and I am a little bit lost with createContext hook.
I created a Api component to fetch data from my backend
export interface List{
id?: string,
sku?: string,
name?: string,
description?: string,
unit_price?: number,
image_url?: string,
active?: boolean,
units_in_stock?: number,
date_created?: Date,
last_updated?: Date,
category?:number
}
export const Context = createContext<List[]>([])
function Api() {
const [product, setProduct] = useState<List[]>([])
useEffect(() => {
const fetchData = async ()=>{
try {
const response = await axios.get('http://127.0.0.1:8000/djassa/products/')
setProduct(response.data)
}
catch (error) {
console.error("Failed to fetch products", error)
}
}
fetchData()
}, [])
return (
<>
< Context.Provider value={product} >
<Home />
</Context.Provider>
</>
)
}
export default Api
Then I wanted to display some of the data into Home Component.
function Home(){
const data = useContext(Context)
console.log(data);
return(
<>
{data.map((product) => (
<p key={product.id}>{product.name}</p>
))}
<p>You just entered home.</p>
</>)
}
export default Home
The problem is when I tried to rend home, it does not work
import 'bootstrap/dist/css/bootstrap.min.css';
import './App.css'
import Home from './assets/component/Home';
import Api from './assets/component/Api';
function App() {
return (
<>
<Home />
</>
)
}
export default App
However, when I add Api component in place of Home component in my App component. it seams to work.
import 'bootstrap/dist/css/bootstrap.min.css';
import './App.css'
import Home from './assets/component/Home';
import Api from './assets/component/Api';
function App() {
return (
<>
<Api />
</>
)
}
export default App