Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to update props in child component after getting values from chrome.storage?

The problem is that my child component is not being re-rendered after I update name state using chrome.storage.sync.get.

So even though name="John" radio button is not checked.

storage.ts:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

export function getName(): Promise<nameInterface> {
  return new Promise((resolve) => {
    chrome.storage.sync.get("name", (response: nameInterface) => {
      resolve(response)
    })
  })
}

popup.tsx:

 const [name, setName] = useState<string>()

  useEffect(() => {
    getName().then((storedName) => {
      setName(storedName)
    })
  }, [])

return (
    <div>
      <RadioButton
 name={name}
      ></RadioButton>
  )

child.tsx:

const RadioButton: React.FC<AppProps> = ({ name}) => {
  const [buttonChecked, setButtonChecked] = useState<string>(name)

  return (
  <input type="radio" checked={buttonChecked==="John"} />
  )
}

>Solution :

It’s re-rendering.

But what happens when this component re-renders? Nothing much. It already captured state from props the first time it rendered, and internally it only ever uses that state, and nothing ever changes that state. Since the state never changed, nothing in the UI changed.

If you want the component to use the prop instead of maintain internal state, get rid of the internal state:

const RadioButton: React.FC<AppProps> = ({name}) => {
  return (
    <input type="radio" checked={name==="John"} />
  )
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading