I have a state variable called list
that updates when setList
is called. SetList
lives under the function AddToList
, which adds a value to the existing values in the list.
As of this moment, the function handleList
executes prior to the state variable setList
even though I have setList
added prior to the function handleList
. What I am trying to achieve is for the setList
to update its list prior to running the handleList
. Could you provide insights on how to fix this?
If you want to test the code, https://codesandbox.io/s/asynchronous-test-mp2fq?file=/Form.js
export default function Form() {
const [list, setList] = useState([]);
const addToList = (name) => {
let newDataList = list.concat(name);
setList(newDataList);
console.log("List: ", list);
handleList();
};
const handleList = async () => {
console.log("Handle List Triggered");
await axios
// .put("", list)
.get("https://api.publicapis.org/entries")
.then((response) => {
console.log("Response: ", response);
})
.catch((error) => {});
};
return (
<AutoComplete
name="list"
label="Add to List"
onChange={(events, values) => {
addToList(values.title);
}}
/>
);
}
As you can tell, the get response
is made prior to updating the list.