I'm new to functional components after spending some huge time with class components.While trying out something, I ran into some problems. How to use componentWillReceiveProps in the context of useEffect hook,
componentWillReceiveProps(nextProps) {
if (_.isEmpty(nextProps.user)) {
this.props.history.push("/signin");
}
this.setState({
selImg: nextProps.meetingData.themeImage,
});
}
Wrap the side effect of changing the route in a useEffect(), and make it dependent on user, so it would react whenever user changes. You also need to history as a dependency, but it wouldn't change.
Assign meetingData.themeImage to a const or use it directly, since the component will rerender anyway if it changes.
const Example = ({ user, history, meetingData }) => {
useEffect(() => {
if (_.isEmpty(user)) {
history.push("/signin");
}
}, [user, history]);
const selImg = meetingData.themeImage;
return (
// JSX
);
}
This could be equivalent to useEffect with dependency in functional component:
useEffect(() => {
if (_.isEmpty(props.user)) {
props.history.push("/signin");
}
setState({
selImg: props.meetingData.themeImage,
});
}, [props.user]);
Below is the functional implementation for your code.
Instead of setState you can use useState, instead of componentWillReceiveProps you can listen to updates of variables using useEffect.
Note useEffect's second argument, the dependencies array. There you can choose what updates will trigger useEffect's first variable (i.e. the callback).
function FunctionalImplementation({ user, history, meetingData }) {
// The functional equivalent of `this.state = { selImg: null }`
const [selImg, setSelImg] = useState(null);
useEffect(() => {
if (_.isEmpty(user)) {
history.push("/signin");
}
// You might want to put this inside an `else` block, just to be more clear
setSelImg(meetingData.themeImage);
// If you want to update `selImg` when `props.meetingData` changes too,
// add it to useEffect's dependencies array
}, [user, history]);
}