1

I am new at React. I have an array of objects that I created from the values of a Form. When I print it in the console it looks fine. but when I try to add that array to a different object, it changes its format in a very strange way. Here's the code:


const [ingredientes, setIngredientes] = useState([]);

const loadIngredient= (value) => {ingredients.push(value); setIngredients(ingredients);}



const LoadIngredient= () => {
        loadIngredient(JSON.stringify({ingredient: ingredient, cant: parseInt(cantidad,10), unit: unidad}));
        console.log('ingredients loaded: ', ingredients)
    }

const RegistrarProducto = () => {

    alert('Producto registrado: '+ JSON.stringify({
      name: name,
      image: image,
      description: description,
      receta: receta,
      ingredients:ingredients}));
  }

this is how it looks:

Producto registrado:

{"name":"Cookies","image":"","description":"The best cookies ever","receta":"this is a test only","ingredients":["{\"ingredient\":\"mantequilla\",\"cant\":100,\"unit\":\"gramos\"}","{\"ingredient\":\"azucar\",\"cant\":300,\"unit\":\"gramos\"}","{\"ingredient\":\"harina\",\"cant\":1,\"unit\":\"tazas\"}"]}

Producto Registrado Object

Can somebody explain to me why that happens? Thanks in advance and sorry for the spanglish.

1 Answer 1

1

What you see is a serialized format of the JSON, since you use JSON.stringify() before passing value to loadIngredient

If you want it to be an object inside your state array, just remove the usage of JSON.stringify

const LoadIngredient= () => {
    loadIngredient({ingredient: ingredient, cant: parseInt(cantidad,10), unit: unidad});
    console.log('ingredients loaded: ', ingredients)
}
Sign up to request clarification or add additional context in comments.

1 Comment

I get it, that was it! Thank you so much!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.