Hi I have a scenario where i need to replace setState callback after setting new state in react hooks with React_hooks in a particular scenario.
The current code is::
const ThemeOptions = () => {
const [previewType, setPreviewType] = useState("Desktop");
const [previewUrl, setPreviewUrl] = useState("");
const [layout, setLayout] = useState(null);
const [saving, setSaving] = useState(false);
const handleSave = (newdata) => {
setLayout(newdata);
setSaving(true);
axios
.put(window.urls.save, this.state.layout)
.then(
function(response) { // i want this to change in hooks
this.setState(
{
layout: response.data,
saving: false,
},
function() {
this.refs["preview"].refresh();
}
);
}.bind(this)
)
.catch(
function(error) {
console.log(error);
setSaving(false);
}.bind(this)
);
}
return (
<div>
<Router>
<div className="theme_options">
<div className="row" style={{ height: 100 + "vh" }}>
<Sidebar
layout={layout}
onSave={handleSave}
onReset={this.handleReset}
previewType={previewType}
onChangeScreen={handlePreviewScreenChange}
saving={saving}
/>
<div className="col main">
<span className="d-none d-md-block">
<Preview
ref="preview"
type={this.state.previewType}
url={this.state.previewUrl}
/>
</span>
</div>
</div>
</div>
</Router>
</div>
)
}
I want the success callback function of axios.put requests to be changed in hooks as in the above code there is usage of setState along with callback in it.
The major code to refactor is::
this.setState(
{
layout: response.data,
saving: false,
},
function() {
this.refs["preview"].refresh();
}
);
I was thinking of doing ::
useEffect(()=> {
// i dont know what to put there...
),[]);
I want the callback in setState() to happen in react hooks. Kindly suggest me an ideal way to do this considering the above code.
setState
byuseEffect
? – Maksym Bezruchkofunction() { this.refs["preview"].refresh(); }
there. See reactjs.org/docs/hooks-effect.html for reference But setState can't be replaced with useEffect - setState is used before render, and useEffect after. The name useEffect is from triggering side-effect like changing page title. – Zydnar