0

i cannot use previous value using useRef hook. previous value is equal to previous value. can someone tell me why?? and what is the solution.

i need to compare previous value of post;

const [selectedPost, setSelectedPost] = useState({ title: "", content: "" });

Following is previous value function

function usePrevious(value) {
    const ref = useRef();
    useEffect(() => {
      ref.current = value;
    });
    return ref.current;
  }
  const prevVal = usePrevious(selectedPost);

Following is the function in which i use previous value

const handleClickUpdate = () => {
    if (prevVal === selectedPost && isEmpty(errors))
      return setEditClicked(false);

    editPost(selectedPost, postId, "original", () => setEditClicked(false));
  };

Edit//

i found out its happening because of this block of code. can someone explain why??

//clear validation errors on typing title or content
  useEffect(() => {
    if (!isEmpty(selectedPost.title) && !isEmpty(selectedPost.content))
      dispatch(saveErrors({}));
  }, [selectedPost, dispatch]);
Basit Minhas
  • 267
  • 1
  • 6
  • 18
  • This [question](https://stackoverflow.com/questions/53446020/how-to-compare-oldvalues-and-newvalues-on-react-hooks-useeffect) should be useful. – Sivaram P Jan 10 '21 at 07:00

1 Answers1

0

It was happening because of this use Effect hook. maybe because selected post chang effect was already in use here so compiler wasnt able to execute the same effect to store previous value since this below code block came first. i removed it and instead restored errors in handle change. This solved my problem.

Previously:

useEffect(() => {
    if (!isEmpty(selectedPost.title) && !isEmpty(selectedPost.content))
      dispatch(saveErrors({}));
  }, [selectedPost, dispatch]);

now:

const handleChange = (event) => {
    const { name, value } = event.target;

    //  clear validation errors on typing title or content
    if (!isEmpty(selectedPost.title) && !isEmpty(selectedPost.content))
      dispatch(saveErrors({}));

    setSelectedPost((prevVal) => {
      return { ...prevVal, [name]: value };
    });
  };
Basit Minhas
  • 267
  • 1
  • 6
  • 18