Reputation: 827
const initData = {
name: "",
class: ""
}
const [currentStudent, setCurrentStudent] = useState({});
useEffect(() => {
// My example code to setState
setCurrentStudent(exampleData)
//The result of currentStudent is {name: "Alex", class: "4"}
}, []);
const [formData, setFormData] = useState({ condition ? currentStudent : initData });
It's mean if true formData
has result is currentStudent
{name: "Alex", class: "4"}
, if false will initData
state.
But result when I tried the code above is an emty object like this {}
.
How can I set formData
state = currentStudent
({name: "Alex", class: "4"})
Upvotes: 3
Views: 109
Reputation: 1243
Please try this one.
const initData = {
name: "",
class: ""
}
const [currentStudent, setCurrentStudent] = useState({});
const [formData, setFormData] =useState({});
useEffect(() => {
setCurrentStudent(exampleData)
setFormData(condition ? exampleData: initData);
}, [condition]); // or use props variable which is used for condition value.
It's aiming to update the functional component when the props change.
As the condition is mostly set from the props, it is needed to set props or condition as parameters in userEffect
like componentWillReceiveProps
.
Upvotes: 1
Reputation: 816
Try this:
const [formData, setFormData] = useState( condition ? currentStudent : initData);
Upvotes: 0
Reputation: 1961
First time component render, init value state will be applied. You have set current user after that. It will not be applied. why dont you set in init of setState:
const [currentStudent, setCurrentStudent] = useState(exampleData);
Or you can set it useEffect
function:
setFormData(condition ? exampleData : initData);
Upvotes: 0
Reputation: 873
i am change code .
const initData = {
name: "",
class: ""
}
const [currentStudent, setCurrentStudent] = useState({});
const [formData, setFormData] =useState({});
useEffect(() => {
setCurrentStudent(exampleData) // My example code to setState
//The result of currentStudent is {name: "Alex", class: "4"}
setFormData(condition ? exampleData: initData);
}, []);
Upvotes: 1