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:
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"} />
)
}
CodePudding user response:
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"} />
)
}