Home > Software engineering >  Replacing value in nested state with react functional components
Replacing value in nested state with react functional components

Time:02-16

I am trying to use update state in a react function component but it is not working. I tried following a tutorial on pluralsite and apply it to my own project. Ideally this code should be finding the product based on the ID number and replacing the total with a new value.

Unfortunately I am getting an error saying that 'productData.find' is not a function and I'm not sure where the code being used for that is. Are there any suggestions on how to solve this issue?

This is what the data looks like. In this example I am saving the first element of the array.

export let data = [
    {
        name: "Name",
        description:
            "",
        products: [
            {
                id: 1,
                name: "Name 1",
                material: 1.05,
                time: 25,
                total: 0,
            },
            {
                id: 2,
                name: "Name 2",
                material: 3,
                time: 252,
                total: 0,
            },
        ],
    },
...
];
function CompareCard({}) {
    index = 0;
    const [productData, setProductData] = useState(data[index]); 

function setTotalUpdate(id) {

        const productPrevious = productData.find(function (rec) {
            return rec.id === id;
        });

        const productUpdated = {
            ...productPrevious,
            total: 1,
        };
        const productNew = productData.map(function (rec) {
            return rec.id === id ? productUpdated : rec;
        });
        setProductData(productNew);
    }
setTotalUpdate(1)
}

CodePudding user response:

When you do

const [productData, setProductData] = useState(data[index])

you don't pass an Array on your state but an Object (the first element of your data so an Object) and Object don't have find method.

Try const [productData, setProductData] = useState([data[index]])

with [] on our useState to put your Object on array

CodePudding user response:

It's because productData is not an array so .find would not work. You want iterate over the products property in your data, so do productData.products.find(...)

  • Related