For example, I add 10 components.
When I click the show logs button on the 5th line, the first 4 components appear on the console.
But even if I click the button on the 5th line, I want all the components to appear on the console.
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import { observer } from "mobx-react-lite";
function App() {
const [component, setComponent] = useState([]);
useEffect(() => {});
const Test = observer(() => {
return (
<div>
<p>
Test <button onClick={testFunction("myFunction"))}>Show logs</button>
</p>
</div>
);
});
function testFunction(a) {
console.log(component);
console.log(a)
}
return (
<div>
{component.map((Input, index) => (
<Input key={index} />
))}
<button onClick={() => setComponent([...component, Test])}>
Click me
</button>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
codesandbox: https://codesandbox.io/s/react-hooks-useeffect-forked-7q15no
It seems like the Observer is getting a previous version of component, which is not consistent with the updated component. In cases like this, useEffect is usually a better option as it updates instantly instead of asynchronously. Refer to the code below which is working:
The updater simply makes the useEffect hook run which logs the latest value of component. The onClick now simply updates the updater.
import React, { useState, useEffect } from "react";
import ReactDOM from "react-dom";
import { observer } from "mobx-react-lite";
function App() {
const [component, setComponent] = useState([]);
const [updater, setUpdater] = useState(0);
useEffect(() => {console.log(component)}, [updater]);
const Test = observer(() => {
return (
<div>
<p>
Test <button onClick={() => setUpdater(updater + 1)}>Show logs</button>
</p>
</div>
);
});
return (
<div>
{component.map((Input, index) => (
<Input key={index} />
))}
<button onClick={() => setComponent([...component, Test])}>
Click me
</button>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);