React and JS in general are new to me, so I'm still kinda bad at this. What I understand the least in this whole situation are React Hooks and the problem with them not updating sometimes. I know things like why and how you have to avoid multiple calls of a setter and stuff like that, but this particular issue is hard for me to understand or even google correctly. Either I find class-based this.state stuff or unanswered questions here.
How to make the hook update, when I need it. For example, this is Autocomplete component from Material-UI. when I select an option in it I want to put its value into newFKSchema const in getTables to work with it. Only first three lines in this method are important for this question. But console.log shows that newFKSchema is empty. And if I choose another option, newFKSchema will have the previous option in it. So there is like a one-turn delay. I don't understand why exactly is that happening and how to make it work like I want. Sorry for messy code, I've already made some attempts to make it work.
If it is not hard for you, after providing a solution please explain it a little.
const allSchemas = [
'',
'ADDITIONAL',
'BOOKKEEPING',
'CB',
'DEPOSIT',
'DOGORG',
'GENERALUSE',
'NSI',
'PAYMENTS',
'PLASTIC',
'SAFECELL',
'SWIFT',
'TARIFF',
];
const [newFKSchema, setNewFKSchema] = React.useState(allSchemas[0]);
const getTables = (schema) => {
var newSchema = schema;
setNewFKSchema(newSchema);
console.log(newFKSchema);
if (newFKSchema !== '') {
superagent
.get('/api/tech')
.query({schema: schema})
.then((response) =>{
if (response.status === 200) {
const newTables = [];
response.body.forEach(e => {newTables.push(e)});
setAllTables(newTables);
}
})
.catch(error => {
if (error.response.statusCode === 400) {
alert("No tables were found!");
}
});
}
}
<FormControl fullWidth>
<Autocomplete
id="autocomplete-schema"
options={allSchemas.slice(1)}
value={newFKSchema}
onChange={(event, value) => {setNewFKSchemaError(false); getTables(value)}} //setNewFKSchema(value);
renderInput={(params) => <TextField {...params} label="Schema name" variant="outlined" fullWidth />} />
<FormHelperText className={classes.formHelper}>
{newFKSchemaError ? "Needs input!" : ''}
</FormHelperText>
</FormControl>