0

I am taking the user input with handleInput function and setting a useState() hook variable named newProduct but when ever I change the value of the input and add it to the newProduct variable it is there with full information but when I console.log() it in another function by which I am sending the data to backend, it is totally empty there.

here is the main code (the full code is so big so I am giving the main code of handleInput function and another function which sends the data to backend.)

newProduct useState variable :

const [newProduct, setNewProduct] = useState({
    productId: props.Products.allProducts.length + 1,
    name: '',
    category: '',
    price: '',
    OriginalPrice: '',
    description: '',
    Mesurements: '',
    Material: '',
    Color: '',
    Work: '',
    StitchType: '',
    Occasion: '',
    printPattern: '',
    SupplierSKU: '',
    supplier: '',
    CountryOfOrigin: '',
    CareGuide: '',
  });

handleInput Function:

let name, value;
  const handleInput = (e) => {
    name = e.target.name;
    value = e.target.value;
    setNewProduct({ ...newProduct, [name]: value });
    console.log(newProduct) // here is totally filled with information which it should be.
  }

Function which sends data to backend

const AddProducts = async (e) => {
    console.log(newProduct); // it's values should be filled with information but it's totally empty.
    e.preventDefault();
    if (newProduct.name.length > 0) { // sending data to backend only if the newProduct have some information
      try {
        const res = await fetch('http://localhost:5000/addProduct', {
          method: 'POST',
          withCredentials: true,
          credentials: 'include',
          headers: {
            'Content-Type': 'application/json'
          },
          body: JSON.stringify({
            "productId": newProduct.productId,
            "name": newProduct.name,
            "category": newProduct.category,
            "price": parseInt(newProduct.price),
            "OriginalPrice": parseInt(newProduct.OriginalPrice),
            "Images": productImages,
            "description": newProduct.description,
            "Mesurements": newProduct.Mesurements,
            "Material": newProduct.Material,
            "Color": newProduct.Color,
            "ColorVariant": colorVariantInputs,
            "Size": newProduct.sizeAvailable,
            "Work": newProduct.Work,
            "StitchType": newProduct.StitchType,
            "Occasion": newProduct.Occasion,
            "printPattern": newProduct.printPattern,
            "SupplierSKU": newProduct.SupplierSKU,
            "supplier": newProduct.supplier,
            "CountryOfOrigin": newProduct.CountryOfOrigin,
            "CareGuide": newProduct.CareGuide
          })
        }).then((response) => { return response.json() })
          .then((data) => {
            if (data) { }
          })
      } catch (error) { }
    }
  }

it's filled with information when I console.log it in the handleInput function: enter image description here

it's empty when I console.log it in the addProducts() function: enter image description here

  • 1
    If your function needs to work with variables, make those variables part of the function parameters and pass them in when you call the function. – Mike 'Pomax' Kamermans May 05 '23 at 16:49
  • 1
    Does this answer your question? [The useState set method is not reflecting a change immediately](https://stackoverflow.com/questions/54069253/the-usestate-set-method-is-not-reflecting-a-change-immediately) – Konrad May 05 '23 at 16:59
  • 1
    Also note that that `console.log(newProduct)` will not immediately reflect the new state, as React will not have updated `newProduct` until the _next_ render call (one of the core principles of React is that _during_ a render pass, all props/state remain fixed, and any updates to them are deferred until the _next_ render pass). However, console.log does not run synchronously, so if your component updates quickly, it might _seem_ like that line's logging the right thing by the time the actual log action happens. The only way to log mutable data "right now" is to log a clone of that data. – Mike 'Pomax' Kamermans May 05 '23 at 17:00
  • @Mike'Pomax'Kamermans it's updated when i called newProduct in console just after setting the variable but it not shows on the another function : (, it's actually already set there. – Priyanshu kuntal May 05 '23 at 17:31
  • @Konrad I am not using `useEffect` anywhere in this and also it not solve my problem brother – Priyanshu kuntal May 05 '23 at 17:32
  • 2
    " it's updated when i called newProduct in console just after setting the variabl" no, it isn't, because you're using React's `useState`, so when you call `setNewProduct` that update will happen _after_ the render pass finishes. What you're seeing is an effect of `console.log` running "whenever the JS scheduler feels like it". If you want to actually debug your code, set breakpoints with var watchers, or console.log snapshots (e.g. `JSON.parse(JSON.stringify(newProduct))` or the like). – Mike 'Pomax' Kamermans May 05 '23 at 18:35
  • @Mike'Pomax'Kamermans brother if my way is wrong then can you please answer this question I am actually new to react if you know how to solve it can you please answer this question brother – Priyanshu kuntal May 06 '23 at 03:56
  • I you are new at React, start with https://react.dev/learn/describing-the-ui and run through those few pages. It's super well written, and will help you far more than SO can. And then when you've run through that in less than a day and you still can't figure out why things are going wrong, you'll now be able to create a much better [mcve] with a problem description based on knowing how react works. But also remember that React is tacked on top of JS: basics like "my function says x is undefined" has nothing to do with React, that's JS variable scoping behaving as it should. – Mike 'Pomax' Kamermans May 06 '23 at 15:38
  • Let us [continue this discussion in chat](https://chat.stackoverflow.com/rooms/253510/discussion-between-priyanshu-kuntal-and-mike-pomax-kamermans). – Priyanshu kuntal May 06 '23 at 15:41

0 Answers0