Skip to content
Advertisement

Not being able to print an array

i created empty array using the React State Hook, the array starts empty and i have 3 functions to (add to the array), (remove the last element of the array) and another to empty the array. The functions seems to work since i logged the result in the console. But when i want to print the array on a paragraph, the array does not show. Can someone give me some feedback? Thanks.

The code is below

JavaScript

Advertisement

Answer

In React, you shouldn’t mutate state. Mutating state is an anti-pattern, not allowed, a big no-no (hope I was clear on this one). What you do, is you create a copy of your state, and call the handler with this new value.

For example:

JavaScript

Should be:

JavaScript

This way, handler was called with a new entity (a new array) so we are ok to go. There are other ways to do this. Let’s do the next one using a callback.

JavaScript

Same principle. You call handler to update the new value.

Lastly, reset could just call handler with an empty array.

JavaScript

Now, let’s speak about two other issues. The first one is naming. When you use the useState hook, by convention, the naming would be something like this:

JavaScript

Lastly, you placed console.logs inside your functions. Those console.logs will log the OLD state. Not the new one.

If you want to have the new one, you need to wrap it in a useEffect, and add inicial to the dependencies array:

JavaScript

I hope it helps.

Advertisement