Search code examples
reactjstypescriptreact-functional-component

props value is populating only after second click of button


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


Solution

  • 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.