In the past, i was writing reactjs code like this:
class App extends Component {
state = { var1:null, var2:null, var3:null };
myfunction1 = async () => {
...
this.setState({ var1:10, var2:20, var3:30 }, this.myfunction2);
}
myfunction2 = async () => {
...
};
render() {
console.log("render");
return (
<div className="App">
{ this.state.var1 }
{ this.state.var2 }
{ this.state.var3 }
</div>
);
}
Now, i am working this way:
const App = () => {
const [var1, setVar1] = useState(null);
const [var2, setVar2] = useState(null);
const [var3, setVar3] = useState(null);
async function init() {
setVar1(10);
setVar2(20);
setVar3(30);
function2();
}
useEffect(() => { init(); }, []);
async function function2() {
}
console.log("render");
return (
<div className="App">
{ var1 }
{ var2 }
{ var3 }
</div>
);
Here are my problems in the second way:
Is there a way to make setVar1, setVar2 and setVar3 in a same call ? The problem is the page will be refreshed 3 times. In the first refresh, var1 will equal to 10, but var2 and var3 will be null. It can cause some problems...
How can i be sure function2 will be called AFTER var1, var2 and var3 will be set ? In the first approach there is a callback function which is called only when states are set. How can i do the same thing in the second approach ?
Thanks