Reputation: 3885
I feel like I'm doing everything right? It seems so simple i feel like I'm missing something. Appreciate any help thank you
function App() {
let jsonData = "a saved page from the database";
return (
<div className="App">
<button onClick={() => {
jsonData = "a different saved page from the database";
}}>
Change jsonData
</button>
<Touchscreen
key={jsonData} // something i tried but still doesn't work
jsonData={jsonData}
/>
</div>
);
}
export const Touchscreen = (props) => {
React.useEffect(() => {
console.log('jsonData: ', props.jsonData); // won't trigger
}, [props.jsonData]);
return (
<div>
<span>{props.jsonData}</span> // never re-renders
</div>
);
}
Upvotes: 0
Views: 60
Reputation:
You need to put your jsonData as a property of the component state and then use setState
to change the value. Calling setState
will cause the component to re-render.
For more information about setState
, take a look at the docs.
Upvotes: 2
Reputation: 11810
The component redeclaresjsonData
on every re-render, you can't preserve the changes on re-renders
. if you want to preserve something through the component lifecycle, state
is the place for it
function App() {
const [jsonData, setJsonData] = useState("a saved page from the database");
return (
<div className="App">
<button onClick={() => {
setJsonData("a different saved page from the database");
}}>
Change jsonData
</button>
</div>
);
}
Upvotes: 4