luckydev
luckydev

Reputation: 149

How to add a string to an array?

const [userOrderCollection, setUserOrderCollection] = useState([{
  url: null
}]);

const onAddedUserOrder = url => {
  if (userOrderCollection[0].url === url) return;
  else {
    setUserOrderCollection([{ ...userOrderCollection,
      url
    }]);
    console.log(userOrderCollection)
  }
};
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

But, the line is added only once, and with the first click, I get an empty array in the console, only with the second click the addition is triggered ...

Upvotes: 0

Views: 57

Answers (4)

apokryfos
apokryfos

Reputation: 40673

You're not actually adding anything to the array, you're constantly creating an array of a single element. In addition your console log will not show the updated state at that point.

Try this:

const [userOrderCollection, setUserOrderCollection] = useState([]);

const onAddedUserOrder = url => {
  if (userOrderCollection.find(user => user.url === url)) return;
  else {
    setUserOrderCollection(prev => ([ ...prev, { url } ]));
  }
};

If you want to see the state after it's been updated you should do so within a useEffect

Upvotes: 2

Tomer Almog
Tomer Almog

Reputation: 3868

You are using the array destruction wrong:

Change

setUserOrderCollection([{ ...userOrderCollection,
  url
}]);

to

setUserOrderCollection([
  ...userOrderCollection,
  {url}
]);

Upvotes: 0

Mat Sz
Mat Sz

Reputation: 2552

You can't console.log right after calling the setUserOrderCollection function since it's asynchronous, calling that function only dispatches the action to take place on a later date.

On another note, to avoid race conditions, you should use the set*((value) => newValue) instead of set*(newValue).

setUserOrderCollection(userOrderCollection => [{ ...userOrderCollection,
      url
}]);

Also, if you want to add something to the array you should use something like that:

setUserOrderCollection(userOrderCollection => [...userOrderCollection, {
      url
}]);

Your code would only expand an array over the only object in an array, which probably isn't something you're looking for.

To log each state change you can use the useEffect hook, like this:

useEffect(() => console.log(userOrderCollection),
    [ userOrderCollection ]
);

Upvotes: 0

David Bradshaw
David Bradshaw

Reputation: 13077

State is updated on the next render of the component, so logging it where you do will show the previous state

Upvotes: 1

Related Questions