-1

I'm doing a social networking project on React.

I wanted to replace one component from class - to functional and use hooks, and a global problem appeared:

When I go to a new user, the page displays the status of the previous one

I use useState() hook, debugged everything, but for some reason when a new status component is rendered, it doesn't update

const ProfileStatus = (props) => {
  const [edditMode, setEdditMode] = useState(false);
  const [status, setValue] = useState(props.status || "Empty");

  const onInputChange = (e) => {
    setValue(e.target.value);
  };
  const activateMode = () => {
    setEdditMode(true);
  };
  const deactivateMode = () => {
    setEdditMode(false);
    props.updateUserStatus(status);
  };

I thought the problem was that the container component was still a class component, but by redoing it, nothing has changed.

Luchi
  • 1
  • 1
    Duplicate of [React.useState does not reload state from props](https://stackoverflow.com/questions/54865764/react-usestate-does-not-reload-state-from-props) – Guy Incognito Feb 17 '23 at 11:25

1 Answers1

0

One way to solve this is by using the useEffect hook to trigger an update when props change. You can use the hook to do comparison between current props and previous props, then update status in the state.

Use this as reference and adapt according to your own code.

const ProfileStatus = (props) => {
  const [edditMode, setEdditMode] = useState(false);
  const [status, setValue] = useState(props.status || "Empty");

  useEffect(() => {
    setValue(props.status || "Empty");
  }, [props.status]);

  const onInputChange = (e) => {
    setValue(e.target.value);
  };
  const activateMode = () => {
    setEdditMode(true);
  };
  const deactivateMode = () => {
    setEdditMode(false);
    props.updateUserStatus(status);
  };
Kreetchy
  • 688
  • 4
  • 14