Показать сообщение отдельно
  #1 (permalink)  
Старый 30.01.2020, 05:43
Новичок на форуме
Отправить личное сообщение для Vlad Kopernikov Посмотреть профиль Найти все сообщения от Vlad Kopernikov
 
Регистрация: 09.01.2020
Сообщений: 2

Как корректно передать переменные с json данными в другой компонент через контекст?
Пытаюсь передать переменные с json данными в компонент для их дальнейшего использования, но натыкаюсь на ошибки. Что следует изменить чтобы переменные с json массивами из Store.js можно было использовать в product.js?
Спасибо за уделенное время! Совсем недавно приступил к изучению, пардон за недальновидность

https://jsfiddle.net/constant101/xu7zdn26/3/

```
//Store export(receiving data from the server and assigning them to variables)
import React, {useState, useEffect} from 'react'
import axios from 'axios'

export const ListContext = React.createContext([]);
export const ItemContext = React.createContext([]);

function Store() {
const [storeProducts, setStoreProducts] = useState([]);
const [detailProduct, setDetailProduct] = useState([]);

useEffect(() => {
axios.get('/products/')
.then(res => {
console.log(res)
setStoreProducts(res.data)
})
},[])
console.log('storeProducts:', storeProducts)

useEffect(() => {
axios.get('/products/roductId')
.then(res => {
console.log(res)
setDetailProduct(res.data)
})
},[])
console.log('detail product:', detailProduct)
return (







);
}
export const detailProduct
//product.js ( file that uses data from the fetch)
import React, { useReducer, createContext, useContext, useState } from 'react';
import {ListContext, ItemContext } from '../Store';
import { useProductActions } from '../actions';
import { SET_PRODUCT_DETAILS } from '../actions/types';

const [storeProducts] = useContext(ListContext);
const [detailProduct] = useContext(ItemContext);

let tempProducts = [];

storeProducts.forEach(item => tempProducts.push({ ...item })
);

const initialState = {
products: tempProducts,
productDetails: { ...detailProduct }
};
console.log(storeProducts)

const productReducer = (state, action) => {
switch (action.type) {
case SET_PRODUCT_DETAILS:
return {
...state,
productDetails: action.payload
};
default:
throw new Error('Invalid action type');
}
};

export const ProductContext = createContext(initialState);

export const useProductState = () => {
return useContext(ProductContext);
};

export const ProductProvider = ({ children }) => {
const [state, dispatch] = useReducer(productReducer, initialState);
const productActions = useProductActions(state, dispatch);
return (

{children}

);
};
Ответить с цитированием