Alex
Alex

Reputation: 827

setState after useEffect() finish and has value

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

Answers (4)

Everest Climber
Everest Climber

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

anon
anon

Reputation: 816

Try this:

const [formData, setFormData] = useState( condition ? currentStudent : initData);

Upvotes: 0

Viet Dinh
Viet Dinh

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

A.R.SEIF
A.R.SEIF

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

Related Questions