Set data in React hooks?

1.2k Views Asked by At

This is my code.

const initialNoticeState = {
    id: props,
    title       : '',
    description : '',
    image : '',
    updated_by  : user.firstName+' '+user.lastName,
    priority    : ''
  };
  const [currentNotice, setCurrentNotice] = useState(initialNoticeState);
  const notice = useSelector(state => state.notices.currentNotice)
  const [noticeImage, setNoticeImage] = useState("");
  const [imgData, setImgData] = useState(null);
  const dispatch = useDispatch();

  useEffect(() => {
   dispatch(noticeActions.getById(props.id))
  }, [props.id]);

I want to setCurrentNotice from notice value, just after dispatch finishes.

Here is the data of notice:

enter image description here

2

There are 2 best solutions below

3
On

I want to setCurrentNotice from notice value, just after dispatch finishes.

useEffect can be used to execute functions when variable is changed.

  useEffect(() => {
   setCurrentNotice(notice)
  }, [notice]); //notice is the dependency
2
On

Just Like that

setCurrentNotice({your current notice data})