Я создаю реакцию. js Приложение для шоппинга и использует жестко закодированные данные. Затем я создал API, содержащий те же данные, которые я хочу использовать вместо этого.
Я хочу, чтобы файл context.js
обращался к массиву {storeProducts, detailProduct}
из файла ./data
. В консоли я могу вернуть массив API с помощью (C), но я не уверен, как позволить context.js
получить к нему доступ.
context. js
import React, { Component } from 'react';
import {storeProducts, detailProduct} from './data';
const ProductContext = React.createContext();
class ProductProvider extends Component {
state ={
products: [],
detailProduct: detailProduct
};
componentDidMount(){
this.storeProducts();
}
storeProducts = () =>{
let tempProducts = [];
storeProducts.forEach(item =>{
const singleItem = {...item};
tempProducts = [...tempProducts,singleItem];
})
this.setState(()=>{
return{products:tempProducts}
})
render() {
return (
<ProductContext.Provider
value={{
...this.state,
handleDetail:this.handleDetail,
addToCart:this.addToCart,
}}>
{this.props.children}
</ProductContext.Provider>
)
}
}
const ProductConsumer = ProductContext.Consumer;
export { ProductProvider, ProductConsumer};
data. js
export const storeProducts = [
{
id: 1,
title: "Nike Air",
img: "img/product-1.png",
price: 70,
company: "Nike",
style: "Mens",
size: 6,
inCart: false,
count: 0,
total: 0
},
export const detailProduct =
{
id: 1,
title: "Nike Air",
img: "img/product-1.png",
price: 70,
company: "Nike",
style: "Mens",
size: 6,
inCart: false,
count: 0,
total: 0
};
C) Возможный ответ ???
async componentDidMount() {
const url = "http://localhost:3001/posts";
const response = await fetch(url);
const data = await response.json();
console.log(data);
}