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
Ad