Any idea of how to make the fetched value from Axios will be the initial value of another state?
I'd try to put it on use effect after it renders the state will update
Here is the code:
const [code, setCode] = useState(0);`enter code here`
useEffect(() => {
const result = data[0] ? data[0].code: 0; // <- fetched from axios
setCode(result);
});
you can make api calls and assign those value to your state by making useEffect similar to componentDidMount:
useEffect(() => {
const result = data[0] ? data[0].code: 0; // <- fetched from axios
setCode(result);
},[]);
This will only be called after your first render. I understand you want the api returned value to be your initial state but this is the best way of doing it.
Got it, I'd just put the data[0] into the deps.
Code: useEffect(() => { const result = data[0]? data[0].code: 0; setcode(result); }, [data[0]]);
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.