Ad
How To Alter State With Information From Clicked Item Using React Context API
Need to navigate and show product details of item that has been clicked. I have the correct item returning in my console log but not sure how to edit/set state and replace dummy text with value of the clicked item. I'm using content API for state management and the data is coming from a separate file that is imported into my Context.js.
Context.js
import React, { useState, createContext } from 'react';
import { storeProducts, detailProduct } from './data';
export const ProductContext = createContext();
export const ProductProvider = (props) => {
const [ products ] = useState(storeProducts);
const [ dummyDetails ] = useState(detailProduct);
const getItem = (id) => {
const product = products.find(item => item.id === id);
return product;
}
const showDetails = (id) => {
const product = getItem(id);
console.log(product);
console.log(dummyDetails);
};
const addToCart = (id) => {
console.log(id);
};
return (
<ProductContext.Provider value={[ products, dummyDetails, showDetails, addToCart ]}>
{ props.children }
</ProductContext.Provider>
);
}
I have my information coming back from the getItem function and the 2 console.logs in showDetails are giving me the dummyDetails and the product details. I need to swap the product for the dummyDetails. Thanks in advance.
Ad
Answer
You can set product by function return from useState
const [ dummyDetails, setProduct ] = useState(detailProduct);
const showDetails = (id) => {
const product = getItem(id);
setProduct(product);
};
Ad
source: stackoverflow.com
Related Questions
- → Import statement and Babel
- → should I choose reactjs+f7 or f7+vue.js?
- → Uncaught TypeError: Cannot read property '__SECRET_DOM_DO_NOT_USE_OR_YOU_WILL_BE_FIRED' of undefined
- → .tsx webpack compile fails: Unexpected token <
- → React-router: Passing props to children
- → ListView.DataSource looping data for React Native
- → React Native with visual studio 2015 IDE
- → Can't test submit handler in React component
- → React + Flux - How to avoid global variable
- → Webpack, React & Babel, not rendering DOM
- → How do I determine if a new ReactJS session and/or Browser session has started?
- → Alt @decorators in React-Native
- → How to dynamically add class to parent div of focused input field?
Ad