I’m building an application in React and I’m having some problems, I want to change some styles of a component that was created with Material UI, Paper, this style should be changed when TYPE_USER is equal to 0, for this I created two useEffect, one to receive and save the data, the other to do the verification and change the styles, this is the code
function SideBarLeft() {
const style = useStyles();
const [disableSearch, setDisableSearch] = useState(false);
const [placeholder, setPlaceholder] = useState('Funcionário ou NIF');
const [funcao, setFuncao] = useState('');
const [nome, setNome] = useState('');
useEffect(() => {
const token = localStorage.getItem('token');
const decoded = jwt_decode(token);
const id = decoded.user.ID;
console.log('id: ' + id)
axios
.get(`${API_BASE_URL}/user/${id}`)
.then((res) => {
setFuncao(res.data.user.TIPO_UTILIZADOR);
setNome(res.data.user.NOME_UTILIZADOR);
})
.catch((err) => {
console.log(err);
}
);
} , []);
useEffect(() => {
if ( funcao === 0 ) {
console.log('funcao: ' + funcao)
setDisableSearch(true);
setPlaceholder(nome);
} else {
setDisableSearch(false);
setPlaceholder('Funcionário ou NIF');
}
}, [ funcao, nome]);
}, []);
This is the code from the Paper where I want to change the styles:
return (
<div className={style.sideBarSearch}>
<Paper component="form" className={disableSearch ? style.sideBarSearchPaperFuncionario : style.sideBarSearchPaper} >
<InputBase
className={style.sideBarSearchInput}
sx={{ ml: 1, flex: 1, input: {
color: 'white',
"&::placeholder": {
opacity: 1,
},
}, }}
placeholder={placeholder}
readOnly={disableSearch}
inputProps={{ style: { color: disableSearch ? '#FFFFFF' : 'black' }}}
/>
{disableSearch ? null : <SearchIcon sx={{ p: '10px', color: '#0093FF'}} />
}
</Paper>
</div>
I’ve tried a few times, mainly with console.log to check if after the if ( funcao == 0 )
, it was being executed, but no, even though the data was being set correctly
2
Answers
I think, the approach you took may be not required, like nesting useEffects() just to change styles.
As far as I have understood, you can change the styles dynamically in react. You can use
sx={ state ? {style1} : {style2}}
inside the mui component i.e conditionally render your styles. The styles will be applied automatically when the state is changed. I hope you don’t need two nested useEffect hook.Why do you need second useEffect? Maybe move logic from it to
axios.then
?