setState after useEffect() finish and has value

Viewed 86
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"})

4 Answers

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);
}, []);

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.

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);

Try this:

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