When I run the useState it is running twice where the first time is giving the empty array[] and the second time is showing the fetch data.
const [configuration, setConfiguration] = useState([]);
useEffect(() => {
getMailinfo();
}, []);
function getMailinfo() {
axios
.get(`${appLocalizer.apiUrl}/wcs/v1/wcs_mail_active`, {
headers: {
"content-type": "application/json",
"X-WP-NONCE": appLocalizer.nonce,
},
})
.then(function (response) {
setConfiguration(response.data);
});
}
console.log(configuration);
{
"mailactive": true,
"ownermail": "[email protected]",
"username": "[email protected]",
"password": "168463517FKJKT1EE13B4CE44B9A90",
"host": "smtp.email.com"
}
It run twice; first [] empty array then the data
Now If I use my fetch data inside another useState its always shows undefined as useState getting empty array first time.
const [toggleState, setToggleState] = useState(configuration.ownermail);
console.log(toggleState); // undefined
return (
<>
<div>Documentation from react:- {configuration.ownermail}</div>
<div>Second run:- {configuration.toggleState}</div>
</>
);
Here 'Documentation from reacting:-' loading first then a after few seconds It shows "Documentation from reacting:- myvalue"
the second div shows nothing and the console its undefined.
My App.js
return (
<div className="wcs_plug" id='wcs_plug_start'>
<WCSTab /> {/* I have already removed the React.StrictMode */}
</div>
);
Can anyone please help here ?? Thanks In advance;
So in short, When I run the useState it is running twice where the first time is giving the empty array[] and the second time is showing the fetch data. Now If I use my fetch data inside another useState it always shows undefined as useState getting an empty array the first time. I want my fetch date to send inside the second useState and also want to run the return only once with valid data. It should not delayed to show the fetch data
setConfiguration(response.data)triggers a re-render and it has your data in it. Use conditional rendering to show things only when you have data.toggleStatewill never change. Use a memo hook if you want something derived from state...const toggleState = useMemo(() => configuration.ownerEmail, [configuration])