The supposed duplicate question only answers the first part(badly) of this question, and not the second. It answers the first part "badly" because JSON.stringify only works for super simple examples. Once the example becomes slighly more complex it opens another problems. Such as "TypeError: Converting circular structure to JSON".
console.log doesn't work as expected. Pay attention to the behaviour in React, CodeSandbox. Link. I stumbled upon the bug while working on my project, which isn't on CodeSandbox, and doesn't use create-react-app(if that matters).
This is not only in React CodeSandbox, but also in Vanila sandbox and probably others.
Below I wrote 2 examples that work as expected.
<!DOCTYPE html>
<html>
<body>
<h1>My First Heading</h1>
<p>My first paragraph.</p>
</body>
<script>
const items = [1, 2];
console.log(items); //okay. Expected=Actual=[1,2]
console.log(items[0]); //okay. Expected=Actual=1
items.reverse();
console.log(items); //okay, Expected=Actual = [2,1]
console.log(items[0]); // okay, Expected=Actual=2
</script>
</html>
Reactjs snippet:
const Why = () => {
const items = [1, 2];
console.log(items); //okay. Expected=Actual [1,2]
console.log(items[0]); //okay. Expected=Actual=1
items.reverse();
console.log(items); //okay, Expected=Actual = [2,1]
console.log(items[0]); // okay, Expected=actual=2
return <div>{items}</div>;
};
ReactDOM.render(
<Why />,
document.getElementById("react")
);
<div id="react"></div>
<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>
- How can I fix that console.log() issue?
- Why does the behaviour differ in different environments?