I am trying to list the query state that a user types in an input box. The problem I am facing here is the value is 1 behind the original. I believe it might be bcoz of the async behavior of the query state that I formed using useState
and setQuery
method which is updating the query(Correct me if my guess is wrong).
Let me know how can I fix this problem.
let queryList = [];
function App() {
const [query, setQuery] = React.useState("");
const handleChange = e => {
setQuery(e.target.value);
queryList.push(query);
console.log(query);
};
return (
<div className="App">
<h1>Hello React</h1>
<input type="text" value={query} onChange={handleChange} />
<div className="query">
{queryList.map((x, id) => (
<li key={id}>{x}</li>
))}
</div>
</div>
);
}
const rootElement = document.getElementById("root");
ReactDOM.render(
<App />
rootElement
);
<script src="https://unpkg.com/react@16.8.6/umd/react.production.min.js"></script>
<script src="https://unpkg.com/react-dom@16.8.1/umd/react-dom.production.min.js"></script>
<div id="root"></div>
Working CodeSandbox Link - https://codesandbox.io/s/tender-mountain-qzgxf
Also, I need one help regarding setting up react code in stack snippets. I added here but its not working let me know what I am doing wrong. Thanks in advance. :)