PandaMastr
PandaMastr

Reputation: 695

Updating state from child to parent and getting the updated state from parent - Typescript, React

As we know React data flow is unidirectional. This concept means that data has one, and only one, way to be transferred to other parts of the application i.e state is passed to the view and to child components. I am performing a state update from my children. But i want to have also the latest updated parent state value inside my child. For example

const Parent:React.FC = () => {
const [parentName, setParentName] = useState<string>('Obi wan');
const updateName = (name: string):void => {
     setParentName(name)
}
return (
     <div>
      <FirstChild name={parentName} updateName={updateName} />
      <SecondChild name={parentName} updateName={updateName} /> 
    </div>
)
}

...

interface IfirstChildProps {
  name: string,
  updateName: (arg: string) => void
}
const firstChild: React.FC<IfirstChildProps> = ({name, updateName}) => {
const [firstChildName, setFirstChildName] = useState<string>('')
useEffect(() => {
   setFirstChildName(name)
},[name])

return (
  <h1> {firstChildName} </h1>
  <button onClick={() => updateName('Luke')}>first child</button>
    )
}
export default firstChild;

...

    interface IsecondChildProps {
      name: string,
      updateName: (arg: string) => void
    }
    const SecondChild: React.FC<IsecondChildProps> = ({name, updateName}) => {
    const [secondChildName, setSecondChildName] = useState<string>('')
    useEffect(() => {
      setSecondChildName(name)
    },[name])
   return (
     <h2> {secondChildName} </h2>
     <button onClick={() => updateName('Vader')}>second child</button>
   )
}
    export default SecondChild;

It seems that something is not quite right. So i would be glat if someone can give me a hand. Thanks a lot . Cheers !

Upvotes: 0

Views: 2423

Answers (1)

Niyi Aromokeye
Niyi Aromokeye

Reputation: 450

When sending your function props, the rendered children components want know it's a function with a string dependency as in your case.

<FirstChild name={parentName} updateName={(text: string) => updateName(text)} />
<SecondChild name={parentName} updateName={(text: string) => updateName(text)} /> 

Then there is no need to set your set your props in a local state. Use the name prop in your child component directly. When there's a click, the parent will update the name in both children component

Upvotes: 0

Related Questions