Learning react so please bear with…
Below code works for me and allows me to set the valueOne as OneOneOne
import etc...
function LoadPage()
{
const [valueOne, setvalueOne] = useState(GetValueOne)
function GetValueOne()
{
return 'OneOneOne';
}
}
The issue I am having is I need to make a call to the server to return the actual value of valueOne on page load… So I have changed to the following:
async function GetValueOne()
{
let oneResult;
await axios.get(`${getBaseUrl()}/One/GetValueOfOne`)
.then(res => {
oneResult= res.data;
});
return oneResult;
}
This is now not working as I have changed the function to async to wait for the axios.get request…Can I update the useState to match this?
If not is there another way to do this please?
2
Answers
You should use
useEffect
in this case.You can initialize the state with some dummy value inside
useState
and add a an effect to update the state valueAlternatively, if your project is getting bigger
You can achieve this using UseEffect hook in ReactJS. You can initialize the state with null value and then update it once the component mounts for the first time.
Sample code:
On above useEffect, I have added empty square bracket which means useEffect only run once when component mounts.
Here, is full code implementation:
Let me know, If you have any questions.