I want to send user to backend in function handleJoin()
.
After setUser is called, the initial data not changed.
How to fix it without using class
App.js
import React, { useState } from "react";
import Join from "./ponents/Join";
const App = () => {
const [user, setUser] = useState({ });
// Send user data to backend
const handleJoin = (input) => {
console.log(input); // > {name: "myname"}
setUser(input); // Not working!
console.log(user); // > { }
// I want to connect backend here
// But the user objet is empty
};
return <Join onJoin={handleJoin} />;
};
export default App;
I want to send user to backend in function handleJoin()
.
After setUser is called, the initial data not changed.
How to fix it without using class
App.js
import React, { useState } from "react";
import Join from "./ponents/Join";
const App = () => {
const [user, setUser] = useState({ });
// Send user data to backend
const handleJoin = (input) => {
console.log(input); // > {name: "myname"}
setUser(input); // Not working!
console.log(user); // > { }
// I want to connect backend here
// But the user objet is empty
};
return <Join onJoin={handleJoin} />;
};
export default App;
Share
Improve this question
asked Apr 10, 2020 at 17:03
DobyDoby
914 silver badges10 bronze badges
1
-
How can we answer this without seeing what the
Join
ponent does, and in particular how itsonJoin
prop is used? – Robin Zigmond Commented Apr 10, 2020 at 17:06
2 Answers
Reset to default 4user
will be updated on the next render after calling setUser
.
import React, { useState, useEffect } from "react";
import Join from "./ponents/Join";
const App = () => {
const [user, setUser] = useState(null);
// This is a side effect that will occur when `user`
// changes (and on initial render). The effect depends
// `user` and will run every time `user` changes.
useEffect(() => {
if (user) {
// Connect to backend here
}
}, [user])
// Send user data to backend
const handleJoin = (input) => {
console.log(input);
setUser(input);
};
return <Join onJoin={handleJoin} />;
};
export default App;
State update is not synchronous so it will not update user object right away but it will be updated asynchronously. So Either you can use input
which is going to be user value to be sent to backend or you can use useEffect()
hook which will be triggered when user
value will be udpated
useEffect(() => {
// this will be triggered whenever user will be updated
console.log('updated user', user);
if (user) {
// connect to backend now
}
}, [user]);
发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744787174a4593696.html
评论列表(0条)