0

in parent functional component:

let [response, setresponse] = useState("undefined");

samplefunction = () => {
    setresponse("completed click");
}

in the child component:

<Button onClick={
    ()=> {
             props.samplefunction();
             console.log(props.response);
         }
}>Sample button</Button>

The problem is the props.response is giving value = completed click only after two clicks of the button. upon single click, it is displaying the value = undefined which is deafult value from parent component

  • The operation to set the state is asynchronous, so it won't be available until after the click handler finishes. The solution in this case is simply that you don't *need* to log the value to the console where you are attempting to do so. The state is still being updated and the component re-rendered. – David Feb 02 '21 at 16:59
  • Actually I need to render something conditionally based on the props value. Is there any alternative where I could perform the same immediately after OnClick ? – Naveen Gorojanam Feb 02 '21 at 17:06
  • The conditional rendering will still work. Try building your conditional rendering instead of just logging to the console. When the state is updated that triggers a re-render of the component, in which the new state will be available to the rendering logic. – David Feb 02 '21 at 17:16
  • Thanks. I went for conditional rendering outside the OnClick method and it worked. thanks for the inputs @David – Naveen Gorojanam Feb 02 '21 at 17:27

1 Answers1

1

You are updating the state on the first click. A state change triggers a rerender of your component, that takes time and wont happen "inline". So

props.samplefunction();
console.log(props.response);

to the time you log the state its still the old state, then components get rerendered and the new state is accessible. Just render the state with {{ props.response }} or log it in the component code, not the click handler or JSX and you will see that you are doing it just right.

Chrissi Grilus
  • 1,099
  • 2
  • 9
  • 21