I need to retrieve data from my API when i change the value in my selector component. So what i did is create a function to fetch my data and i call it in my selector 'onChange'. Now my problem is that in my fetch function i use a variable that i set right before i call it. And when i change the selector value for the first time my useState variable is not set (or not detected by my app) and when i change value for the second time, it finally works. How can i resolve that ?
Selector Component :
<Select
labelId="demo-statut-label"
id="demo-statut"
defaultValue={""}
value={projetName}
onChange={handleSelectProjectChange}
input={<OutlinedInput label="Projet"/>}
MenuProps={MenuProps}
>
{projets.map((projet) => (
<MenuItem
value={projet}
>
{projet.nom}
</MenuItem>
))}
</Select>
onChange function :
const handleSelectProjectChange = (event) => {
setProjetName(event.target.value);
getClientByProject();
};
Fetch Function :
function getClientByProject() {
axios
.get(API_URL_CLIENT_BY_ACTIVITE + projetName.id)
.then((response) => {
if(response.status === 200) {
setClient(response.data);
console.log('Response : ', response.data);
}
})
.catch((error) => {
console.log(error);
})
}
useState :
const tab = projets !== null && projets !== undefined && projets.length > 0 ? projets[0] : {}
const [projetName, setProjetName] = useState(tab);
There is a hook in react called useContext, you should try and use that, it will remove all future instances of "state hasn't updated yet". Meanwhile the quickest fix for your current troubles is this...
onChangeFunction
const handleSelectProjectChange = (event) => {
setProjetName(event.target.value);
getClientByProject(e.target.value);
};
FetchFunction
function getClientByProject(project) {
axios
.get(API_URL_CLIENT_BY_ACTIVITE + projetName.id)
.then((response) => {
if(response.status === 200) {
setClient(response.data);
console.log('Response : ', response.data);
}
})
.catch((error) => {
console.log(error);
})
}
Explanation: I just passed the data as an argument to the function which makes sure that the Function always has the current data.